Often, you may want to modify existing datetime objects to represent a different date and time. This recipe includes code to demonstrate this.
How to do it…
Follow these steps to execute this recipe:
- Import the necessary modules from the Python standard library:
>>> from datetime import datetime
- Fetch the current timestamp. Assign it to dt1 and print it:
>>> dt1 = datetime.now()
>>> print(dt1)
We get the following output. Your output would differ:
2020-08-12 20:55:46.753899
- Create a new datetime object by replacing the year, month, and day attributes of dt1. Assign it to dt2 and print it :
>>> dt2 = dt1.replace(year=2021, month=1, day=1)
>>> print(f'A timestamp from 1st January 2021: {dt2}')
We get the following output. Your output would differ:
A timestamp from 1st January 2021: 2021-01-01 20:55:46.753899
- Create a new datetime object by specifying all the attributes directly. Assign it to dt3...