How to add seconds on a datetime value in Python?

后端 未结 2 660
太阳男子
太阳男子 2020-12-10 11:21

I tried modifying the second property, but didn\'t work.

Basically I wanna do:

datetime.now().second += 3
相关标签:
2条回答
  • 2020-12-10 11:44

    You cannot add seconds to a datetime object. From the docs:

    A DateTime object should be considered immutable; all conversion and numeric operations return a new DateTime object rather than modify the current object.

    You must create another datetime object, or use the product of the existing object and a timedelta.

    0 讨论(0)
  • 2020-12-10 11:52

    Have you checked out timedeltas?

    from datetime import datetime, timedelta
    x = datetime.now() + timedelta(seconds=3)
    x += timedelta(seconds=3)
    
    0 讨论(0)
提交回复
热议问题