0

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

2
  • what's utc_delta? Commented Apr 17, 2022 at 2:22
  • I think the use of the pytz for timezone is what you need to convert between local vs UTC Commented Apr 17, 2022 at 3:20

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Not sure why it output the same time: 2022-04-12 20:43:34.342000 -> 2022-04-12 20:43:34.342000
Make sure that the timezone is being initialized accurately. Python might believe that the time is already at UTC+0.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.