1

I have a dataset with timestamps in the format:

`'4/17/2020 5:55:00 AM'`

Please note there are 2 spaces between YYYY and HH fields. The original time is in 'US/Eastern' timezone. I am trying to convert it to IST (Indian Standard Time). This should be 'Asia/Kolkata' from pytz

The code below is not working, and I have tried multiple versions of it. Even conversion to UTC is failing. The code block is:

`
est_ts = '4/17/2020 5:55:00 AM'
est = pytz.timezone('US/Eastern')
ist = pytz.timezone('Asia/Kolkata')
print(dt.datetime.strptime(est_ts, '%m/%d/%Y  %I:%M:%S %p').astimezone(ist).strftime('%Y-%m-%d %H:%M:%S'))
`

This gives an output of:

`2020-04-17 07:25:00`

While the correct output should be:

`2020-04-17 15:25:00`

What is wrong with this code? Much appreciated.

1
  • the localize() method is the way to go, see drec4s answer below. See here on why you should also normalize(). Commented Apr 18, 2020 at 13:47

1 Answer 1

3

You first need to localize the original timestamp, so that you can normalize to the desired location:

import datetime as dt
import pytz

est_ts = '4/17/2020 5:55:00 AM'
est = pytz.timezone('US/Eastern')
ist = pytz.timezone('Asia/Kolkata')

est_dt = est.localize(dt.datetime.strptime(est_ts, '%m/%d/%Y  %I:%M:%S %p'))
ist_dt = ist.normalize(est_dt.astimezone(ist))

print(ist_dt.strftime('%Y-%m-%d %H:%M:%S'))
#2020-04-17 15:25:00
Sign up to request clarification or add additional context in comments.

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.