I would like to convert datetime to UTC time. I try below code but the output looks like not correct:
import datetime
import pandas as pd
def str2dt(tstr):
dt = datetime.datetime.strptime(tstr, '%m-%d %H:%M:%S.%f')
return dt
ts = "04-12 20:43:34.342"
dt = str2dt(ts)
utc_delta = datetime.datetime.utcnow() - datetime.datetime.now()
utc = dt - utc_delta
print(dt,'->',utc)
Current output:
1900-04-12 20:43:34.342000 -> 1900-04-12 15:43:34.342001
The expected output time is 1900-04-12 02:43:34.342001
CodePudding user response:
Should be plus the delta:
import datetime
import pandas as pd
def str2dt(tstr):
dt = datetime.datetime.strptime(tstr, '%m-%d %H:%M:%S.%f')
return dt
ts = "04-12 20:43:34.342"
dt = str2dt(ts)
utc_delta = datetime.datetime.utcnow() - datetime.datetime.now()
utc = dt utc_delta
print(dt,'->',utc)
Output:
1900-04-12 20:43:34.342000 -> 1900-04-13 01:43:34.341999
CodePudding user response:
It looks like you would be better off using isoformat()
on your datetime
:
utc = dt.isoformat(sep=' ') # The normal date-time separator is 'T', but that isn't very readable
print(f"{dt} -> {utc}")
This gives you the answer you're looking for.
If you still need the UTC offset, consider using datetime.datetime.utcoffset()
.