This recipe demonstrates the conversion of the datetime objects into strings which finds application in printing and logging. Also, this is helpful while sending 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
- Fetch the current timestamp along with time zone information. Assign it to now and print it:
>>> now = datetime.now().astimezone()
- Cast now to a string and print it::
>>> print(str(now))
We get the following output. Your output may differ:
2020-08-12 20:55:48.366130+05:30
- Convert now to a string with a specific date-time format using strftime() and print it:
>>> print(now.strftime("%d-%m-%Y %H:%M:%S %Z"))
We get the following output. Your output may differ:
12-08-2020 20:55:48 +0530
How it works...
In step 1, you import the datetime class...