Convert a datatime with milliseconds from a given data and a fiven fractional seconds

82 Views Asked by At

I have a given data, for example:

"2021-12-01 12:00:00" (i.e., %Y-%m-%d %H:%M:%S)

and a given millisecond: 3599.9. I wish to add this millisecond to the previus date in order to have the following format:

%Y-%m-%d %H:%M:%S.%f or %Y-%m-%d %H:%M:%S:%f

I found some example, but all starting with datetime.utcnow(). For example:

>>> from datetime import datetime
>>> (dt, micro) = datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f').split('.')
>>> "%s.%03d" % (dt, int(micro) / 1000)
'2016-02-26 04:37:53.133'
1

There are 1 best solutions below

3
P.W On

Here's an example of how you could achieve that:

from datetime import datetime, timedelta

# Your initial date and time as a string
time_str = "2021-12-01 12:00:00"

# Convert the string to a datetime object
time_dt = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')

# Milliseconds to add
milliseconds = 3599.9

# Convert the milliseconds to a timedelta and add it to the datetime
time_dt += timedelta(milliseconds=milliseconds)

# Convert the datetime back to a string
new_time_str = time_dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]  # The [:-3] trims the last three digits to give milliseconds precision

print(new_time_str)