简体   繁体   中英

Convert UTC+0 to other time zone Python

I have a time string obtained from API, it's UTC+0. I would like to change to other time zone. I have tried below but it doesn't work. Could you please give me some idea? many thanks.

utc0time='2021-04-17T15:50:14.614646+00:00'
dt = datetime.strptime('utc0time', '%Y-%m-%dT%H:%M:%S%z'). #it results as an error, not match the format
time.mktime(dt.timetuple())
calendar.timegm(dt.timetuple())

You could actually use timedelta in datetime module to +/- number of hours to achieve the time in other timezone you wish.

Here is an example where you can use timedelta : https://www.geeksforgeeks.org/python-datetime-timedelta-function/

thanks for the comments and it gave me the idea. Because i only need to convert from one time zone to another one, i don't need to convert to multi-timezone. I don't use pytz this time. I used a silly method, changed the str to timestamp first, then used timedelta to adjust the hours. Below is my final code.

utc0time='2021-04-17T15:50:14.614646+00:00'
utc0time = utc0time[:-13]
timestamp = time.mktime(time.strptime(utc0time, '%Y-%m-%dT%H:%M:%S'))
datatimeformat = datetime.fromtimestamp(timestamp)
utc8time = datatimeformat + timedelta(hours = 8)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM