![]() |
VOOZH | about |
To convert a timestamp string to a datetime object in Python, we parse the string into a format Python understands. This allows for easier date/time manipulation, comparison and formatting. For example, the string "2023-07-21 10:30:45" is converted into a datetime object representing that exact date and time.
Let’s explore simple and efficient ways to do this.
datetime.strptime() is the most common way to convert a date-time string into a datetime object. You provide the string and its format.
2023-07-21 10:30:45
Explanation: s holds the timestamp string. We use strptime() with the format "%Y-%m-%d %H:%M:%S" to parse it into a datetime object dt.
pandas.to_datetime() is powerful for working with large datasets or performing operations in dataframes, but can also be used for single string conversion.
2023-07-21 10:30:45
Explanation: s holds the timestamp string. pd.to_datetime() converts it directly into a pandas Timestamp object, which behaves like a datetime object.
The dateutil module provides powerful parsing without specifying the format.
2023-07-21 10:30:45
Explanation: s is parsed automatically by parser.parse(), which intelligently detects the format and returns a datetime object.
If the timestamp string is in ISO 8601 format (i.e., "YYYY-MM-DD HH:MM:SS"), fromisoformat() is the cleanest and most efficient method to convert it to a datetime object.
2023-07-21 10:30:45
Explanation: s holds a string in ISO format. datetime.fromisoformat(s) directly parses the string into a datetime object dt.
Related articles