The datetime module provides a datetime class, which can be used to accurately capture information relating to timestamps, dates, times, and time zones. In this recipe, you will create datetime objects in multiple ways and introspect their attributes.
How to do it…
Follow these steps to execute this recipe:
- Import the necessary module from the Python standard library:
>>> from datetime import datetime
- Create a datetime object holding the current timestamp using the now() method and print it:
>>> dt1 = datetime.now()
>>> print(f'Approach #1: {dt1}')
We get the following output. Your output will differ:
Approach #1: 2020-08-12 20:55:39.680195
- Print the attributes of dt1 related to date and time:
>>> print(f'Year: {dt1.year}')
>>> print(f'Month: {dt1.month}')
>>> print(f'Day: {dt1.day}')
>>> print(f'Hours: {dt1.hour}')
>>> print(f&apos...