Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add seconds on a datetime value in Python?

Tags:

python

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

Basically I wanna do:

datetime.now().second += 3
like image 475
Joan Venge Avatar asked Apr 24 '09 21:04

Joan Venge


People also ask

How do I show time in seconds in Python?

Current Time in Seconds Using time.Use the time. time() function to get the current time in seconds since the epoch as a floating-point number. This method returns the current timestamp in a floating-point number that represents the number of seconds since Jan 1, 1970, 00:00:00. It returns the current time in seconds.

How do you add minutes to a datetime?

Use the timedelta() class from the datetime module to add minutes to datetime, e.g. result = dt + timedelta(minutes=10) . The timedelta class can be passed a minutes argument and adds the specified number of minutes to the datetime.


2 Answers

Have you checked out timedeltas?

from datetime import datetime, timedelta
x = datetime.now() + timedelta(seconds=3)
x += timedelta(seconds=3)
like image 64
Silfheed Avatar answered Oct 01 '22 10:10

Silfheed


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.

like image 28
vezult Avatar answered Oct 01 '22 09:10

vezult