'python - convert datetime to UTC time
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
Solution 1:[1]
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().
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | triskofwhaleisland |
| Solution 2 | beetlej |
