Home > Software engineering >  datetime.strptime function in python
datetime.strptime function in python

Time:12-17

I am trying to obtain the time in the following way using the 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 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 to resolve it as the time dataset contains "IST" and %Z is not working for it.

CodePudding user response:

If you are interesting format data with the IST try to use pytz

As example

import pytz
from datetime import datetime

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

t1 = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S %Z")

ist = pytz.timezone("Africa/Abidjan") #full list is getting by pytz.all_timezones

t1_local = ist.localize(t1)

print('Start time:', t1_local.time())

Otherwise the datetime.strptime is expecting specific format

As example

from datetime import datetime

start_time = "2021-07-31 09:43:23  0530"

t1 = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S %z")
print('Start time:', t1.time())

CodePudding user response:

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
  • Related