0

I am trying to obtain the time in the following way using this Python code:

from datetime import datetime
start_time="2021-07-31 09:43:23 IST"

# convert time string to datetime
t1 = datetime.strptime(start_time,"%Y-%m-%d %H:%M:%S %Z")
print('Start time:', t1.time())

But I get an error:

ValueError: time data '2021-07-31 09:43:23 IST' does not match format '%Y-%m-%d %H:%M:%S %Z'

How should I resolve it, as the time dataset contains "IST" and %Z is not working for it.

realhuman
  • 137
  • 1
  • 8
  • the behavior of `%Z` can be unpredictable; you can use it *sometimes* to ignore abbreviated time zone names such as "IST". dateutil's [parse](https://dateutil.readthedocs.io/en/stable/parser.html) with a [tzinfos mapping](https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.parse) might be the better option to strptime here. – FObersteiner Dec 19 '22 at 08:26

1 Answers1

0

Code:-

from datetime import datetime
import pytz
UTC = pytz.utc
timeZ_Kl = pytz.timezone('Asia/Kolkata')
dt_Kl = datetime.now(timeZ_Kl)
utc_Kl = dt_Kl.astimezone(UTC)
print(dt_Kl.strftime('%Y-%m-%d %H:%M:%S %Z'))

Output:-

2022-12-17 13:43:52 IST
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20