How to add seconds on a datetime value in Python?
Question:
I tried modifying the second property, but didn’t work.
Basically I wanna do:
datetime.now().second += 3
Answers:
Have you checked out timedeltas?
from datetime import datetime, timedelta
x = datetime.now() + timedelta(seconds=3)
x += timedelta(seconds=3)
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.
The datetime module supplies classes for manipulating dates and times.
But two different classes exist in the datetime:
the class datetime.datetime. This class combines dates and time.
the class datetime.timedelta: A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.
datetime.second – method second returns second for the date, but it won’t be a timedelta.
You should change type of class form datetime to timedelta.
example:
x = datetime.now() + timedelta(seconds=3)
After that you can use compound addition:
x += timedelta(seconds=3
I tried modifying the second property, but didn’t work.
Basically I wanna do:
datetime.now().second += 3
Have you checked out timedeltas?
from datetime import datetime, timedelta
x = datetime.now() + timedelta(seconds=3)
x += timedelta(seconds=3)
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.
The datetime module supplies classes for manipulating dates and times.
But two different classes exist in the datetime:
the class datetime.datetime. This class combines dates and time.
the class datetime.timedelta: A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.
datetime.second – method second returns second for the date, but it won’t be a timedelta.
You should change type of class form datetime to timedelta.
example:
x = datetime.now() + timedelta(seconds=3)
After that you can use compound addition:
x += timedelta(seconds=3