1

I'm trying to convert following string into datetime format

work_date="Sun Aug 23 20:16:44 IST 2020"
dt_new=datetime.datetime.strptime(work_date,"%a %b %d %H:%M:%S %Z %Y")
print(dt_new)

But I am always getting timedata does not match the format. I tried replacing IST with GMT, it works. Also tried replacing IST with 'Asia/Kolkata' but it still doesn't work. I wanted to know if there is some way to register IST under %Z format.

alex_noname
  • 26,459
  • 5
  • 69
  • 86
Dragovic
  • 39
  • 6
  • Does this answer your question? [Display the time in a different time zone](https://stackoverflow.com/questions/1398674/display-the-time-in-a-different-time-zone) – toydarian Aug 20 '20 at 06:55

1 Answers1

1

strptime only accepts certain values for %Z:

  1. any value in time.tzname for your machine's locale
  2. the hard-coded values UTC and GMT

You could use UTC and convert it by pytz third library:

import datetime
import pytz

work_date = "Sun Aug 23 20:16:44 UTC 2020"
dt_new = datetime.datetime.strptime(work_date, "%a %b %d %H:%M:%S %Z %Y")
dt_new = dt_new.astimezone(pytz.timezone("Asia/Kolkata"))
print(dt_new)

Update: Also you can use dateutil module:

from dateutil.parser import parse
from dateutil.tz import gettz
tzinfos = {"IST": gettz("Asia/Kolkata")}
print(parse("Sun Aug 23 20:16:44 IST 2020", tzinfos=tzinfos))
alex_noname
  • 26,459
  • 5
  • 69
  • 86