This recipe demonstrates the conversion of well-formatted strings into datetime objects. This finds application in reading timestamps from a file. Also, this is helpful while receiving timestamps as JSON data over web APIs.
How to do it…
Execute the following steps for this recipe:
- Import the necessary modules from the Python standard library:
>>> from datetime import datetime
- Create a string representation of timestamp with date, time, and time zone. Assign it to now_str:
>>> now_str = '13-1-2021 15:53:39 +05:30'
- Convert now_str to now, a datetime.datetime object. Print it:
>>> now = datetime.strptime(now_str, "%d-%m-%Y %H:%M:%S %z")
>>> print(now)
We get the following output:
2021-01-13 15:53:39+05:30
- Confirm that now is of the datetime type:
>>> print(type(now))
We get the following output:
<class 'datetime.datetime'>
How it works...
In step 1, you...