Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add N milliseconds to a datetime in Python

I'm setting a datetime var as such:

fulldate = datetime.datetime.strptime(date + ' ' + time, "%Y-%m-%d %H:%M:%S.%f") 

where date and time are string of the appropriate nature for datetime. How can I increment this datetime by N milliseconds?

like image 533
WildBill Avatar asked Jul 02 '14 04:07

WildBill


People also ask

How do you represent milliseconds in a date format in Python?

strptime() function in python converts the string into DateTime objects. The strptime() is a class method that takes two arguments : string that should be converted to datetime object.

How do I add seconds to datetime?

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

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

Use timedelta

To increment by 500 ms:

fulldate = datetime.datetime.strptime(date + ' ' + time, "%Y-%m-%d %H:%M:%S.%f") fulldate = fulldate + datetime.timedelta(milliseconds=500) 

You can use it to increment minutes, hours, days etc. Documentation:

https://docs.python.org/2/library/datetime.html#timedelta-objects

like image 169
14 revs, 12 users 16% Avatar answered Sep 19 '22 20:09

14 revs, 12 users 16%


use timedelta:

timedelta(microseconds=1000) #1 milli second 
like image 38
venpa Avatar answered Sep 20 '22 20:09

venpa