官术网_书友最值得收藏!

Modifying datetime objects

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:

  1. Import the necessary modules from the Python standard library:
>>> from datetime import datetime
  1. 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
  1. 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
  1. Create a new datetime object by specifying all the attributes directly. Assign it to dt3 and print it:
>>> dt3 = datetime(year=2021, 
month=1,
day=1,
hour=dt1.hour,
minute=dt1.minute,
second=dt1.second,
microsecond=dt1.microsecond,
tzinfo=dt1.tzinfo)
print(f'A timestamp from 1st January 2021: {dt3}')

We get the following output. Your output would differ:

A timestamp from 1st January 2021: 2021-01-01 20:55:46.753899
  1. Compare dt2 and dt3:
>>> dt2 == dt3

We get the following output.

True

How it works...

In step 1, you import the datetime class from the datetime module. In step 2, you fetch the current timestamp using the now() method of datetime and assign it to a new attribute, dt1. To get a modified timestamp from an existing datetime object, you can use the replace() method. In step 3, you create a new datetime object dt2, from dt1, by calling the replace() method. You specify the attributes to be modified, which are year, month, and day. The remaining attributes remain as it is, which are an hour, minute, second, microsecond, and timezone. You can confirm this by comparing the outputs of step 2 and step 3. In step 4, you create another datetime object, dt3. This time you call the datetime constructor directly. You pass all the attributes to the constructor such that the timestamp created is the same as dt2. In step 5, you confirm that dt2 and dt3 hold exactly the same timestamp by using the == operator, which returns True.

主站蜘蛛池模板: 津市市| 宜宾县| 紫阳县| 伊宁市| 安多县| 青冈县| 丁青县| 淮北市| 乐山市| 乳源| 高唐县| 仁布县| 淮滨县| 横山县| 固安县| 宝坻区| 奉贤区| 广德县| 昌邑市| 湖南省| 海宁市| 江西省| 吐鲁番市| 柳林县| 阿鲁科尔沁旗| 香格里拉县| 伊通| 任丘市| 格尔木市| 庆阳市| 新宁县| 靖安县| 原平市| 弥勒县| 章丘市| 寻甸| 岳池县| 遵义市| 北安市| 惠来县| 新绛县|