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.
Using datetime.strptime()
datetime.strptime()is the most common way to convert a date-time string into a datetime object. You provide the string and its format.
Pythonfromdatetimeimportdatetimes="2023-07-21 10:30:45"dt=datetime.strptime(s,"%Y-%m-%d %H:%M:%S")print(dt)
Output2023-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 objectdt.
Using pandas.to_datetime()
pandas.to_datetime() is powerful for working with large datasets or performing operations in dataframes, but can also be used for single string conversion.
Pythonimportpandasaspds="2023-07-21 10:30:45"dt=pd.to_datetime(s,format="%Y-%m-%d %H:%M:%S")print(dt)
Output2023-07-21 10:30:45
Explanation: sholds the timestamp string.pd.to_datetime() converts it directly into a pandas Timestamp object, which behaves like a datetime object.
Using dateutil.parser.parse()
The dateutil moduleprovides powerful parsing without specifying the format.
Pythonfromdateutilimportparsers="2023-07-21 10:30:45"dt=parser.parse(s)print(dt)
Output2023-07-21 10:30:45
Explanation: s is parsed automatically by parser.parse(), which intelligently detects the format and returns a datetime object.
Using datetime.fromisoformat()
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.
Pythonfromdatetimeimportdatetimes="2023-07-21 10:30:45"dt=datetime.fromisoformat(s)print(dt)
Output2023-07-21 10:30:45
Explanation: sholds a string in ISO format.datetime.fromisoformat(s)directly parses the string into a datetime objectdt.
Related articles
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice