简体   繁体   中英

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: 1 900-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

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() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM