简体   繁体   中英

Converting a Python datetime object that is in utc to local time

I want to show expiry dates for SSL certificates to the user. These expiry dates are in UTC, so when the expiry date is today at noon, it will show 12/08/2020 12:00:00 . However, since I am in the Berlin timezone, that means the certificate will actually expire at 14:00:00 localtime, which is what I want to show to the user. I tried the following:

end_date = certificate_end_date.replace(tzinfo=timezone.utc).astimezone(tz=None)

But since the certificate is valid until 2045, this produces the following error message:

OverflowError: timestamp out of range for platform time_t

I searched and people suggested just using a timedelta, but that is complicated again due to daylight savings time. There has to be a proper way to do this? I am using Python3.7.

I solved it by calculating the timedelta as recommended elsewhere, although it still looks kind of ugly to me:

 from datetime import datetime, timezone

 now = datetime.now()
 offset = now.replace(tzinfo=timezone.utc) - now.astimezone(timezone.utc)

 localtime = utc_time + offset

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