-2

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())
Galaxy Lam
  • 53
  • 7
  • 2
    That won't work because the string `'utc0time`' is not even *close* to a legal time expression. You need to use the variable, not a string of the same characters. – Prune Apr 18 '21 at 05:23
  • 1
    Have you tried using `pytz`. See: https://stackoverflow.com/questions/10997577/python-timezone-conversion – astrochun Apr 18 '21 at 05:40
  • Does this answer your question? [Python Timezone conversion](https://stackoverflow.com/q/10997577/6045800) – Tomerikoo Apr 18 '21 at 15:15

2 Answers2

1

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/

ShengHow95
  • 236
  • 1
  • 5
  • Sure, but `pytz` is more robust as once can specify the timezone rather than have to look up the differences. – astrochun Apr 18 '21 at 05:41
0

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)
Galaxy Lam
  • 53
  • 7