Joan Venge
Joan Venge

Reputation: 331032

How to add seconds on a datetime value in Python?

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

Basically I wanna do:

datetime.now().second += 3

Upvotes: 32

Views: 53497

Answers (3)

Volk
Volk

Reputation: 174

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

Upvotes: 0

vezult
vezult

Reputation: 5243

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.

Upvotes: 3

Silfheed
Silfheed

Reputation: 12201

Have you checked out timedeltas?

from datetime import datetime, timedelta
x = datetime.now() + timedelta(seconds=3)
x += timedelta(seconds=3)

Upvotes: 85

Related Questions