How do I round a datetime
variable like this one:
x = datetime.now()
which produces something like this:
2022-05-04 15:36:01.055696
to something like this?
2022-05-04 15:36:01.057
CodePudding user response:
In case you want to modify a datetime
object, you can round its .microsecond
attribute:
x = datetime.now()
print(x.isoformat(' '))
# 2022-05-04 15:36:01.055696
x = x.replace(microsecond=round(x.microsecond / 1000) * 1000)
print(x.isoformat(' '))
# 2022-05-04 15:36:01.056
In any case (even without modifying the object and rounding the microseconds), to get the representation you want you can format it with the appropriate method:
x.isoformat(' ', timespec='milliseconds')
# 2022-05-04 15:36:01.056
Note that modifying the object using round(x.microsecond / 1000) * 1000
for the microseconds will round them to the closest millisecond. If you just want to truncate the microseconds instead, use x.microsecond // 1000 * 1000
.
CodePudding user response:
If you just want to remove the last few characters you could do:
print(x.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
The formatting str is the default which is what you are seeing in the output
CodePudding user response:
You can convert it to a unix timestamp and then round the number to 3 decimal places.
from datetime import datetime
x = '2022-05-04 15:36:01.055696'
# Convert to datetime object
d = datetime.strptime(x, '%Y-%m-%d %H:%M:%S.%f')
# Convert to rounded unix timestamp
ts = datetime.fromtimestamp(round(d.timestamp(), 3))
# You know have rounded datetime object, you can convert back to string with
ts.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
CodePudding user response:
Pandas timestamp has a built in-function for this. Make the timestamp a timestamp object then use round.
import pandas as pd
x = '2022-05-04 15:36:01.055696'
ts = pd.Timestamp(x)
ts_rounded = ts.round(freq='L')
print(ts_rounded) 2022-05-04 15:36:01.056000