11/23/2023 0 Comments Chicago time zone in gmtTo convert a time in one timezone to another timezone in Python, you could use datetime.astimezone(): time_in_new_timezone = time_in_old_timezone.astimezone(new_timezone) Then: from backports.zoneinfo import ZoneInfo There is a backport to allow use in Python 3.6 to 3.8: sudo pip install backports.zoneinfo Windows has no system time zone database, so here an extra package is needed: pip install tzdata If astimezone gets a timezone-unaware input, it will assume it is local time, which can lead to errors: > datetime.utcnow() # UTC - NOT timezone-aware!!ĭatetime.datetime(2020, 6, 1, 22, 39, 57, 376479) I recommend only requesting timezone-aware values from them using the keyword tz=ZoneInfo('localtime'). Some functions such as now() and utcnow() return timezone-unaware datetimes, meaning they contain no timezone information. > d.astimezone(ZoneInfo('Europe/Berlin')) # 12:00 in Cali will be 20:00 in Berlinĭatetime.datetime(2020, 10, 31, 20, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin')) Python 3.9 adds the zoneinfo module so now only the the standard library is needed! > from zoneinfo import ZoneInfo Utcmoment = localmoment.astimezone(pytz.utc)Įxcept as e: Localmoment = localtimezone.localize(localmoment_naive, is_dst=None) Localtimezone = pytz.timezone('Australia/Adelaide') localmoment_naive = datetime.strptime(' 14:05:10', localFormat) So, with the moment of interest in the local timezone (a time that exists), you convert it to utc like this ( reference). Print(localDatetime.strftime(localFormat)) LocalDatetime = utcmoment.astimezone(pytz.timezone(tz)) # print "utcmoment_naive: ".format(utcmoment)) Utcmoment = utcmoment_naive.replace(tzinfo=pytz.utc) Then you can use astimezone to convert to the timezone of interest ( reference). I have found that the best approach is to convert the "moment" of interest to a utc-timezone-aware datetime object (in python, the timezone component is not required for datetime objects).
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |