Posts

Showing posts with the label Timezone

Convert A Python UTC Datetime To A Local Datetime Using Only Python Standard Library?

Answer : In Python 3.3+: from datetime import datetime, timezone def utc_to_local(utc_dt): return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None) In Python 2/3: import calendar from datetime import datetime, timedelta def utc_to_local(utc_dt): # get integer timestamp to avoid precision lost timestamp = calendar.timegm(utc_dt.timetuple()) local_dt = datetime.fromtimestamp(timestamp) assert utc_dt.resolution >= timedelta(microseconds=1) return local_dt.replace(microsecond=utc_dt.microsecond) Using pytz (both Python 2/3): import pytz local_tz = pytz.timezone('Europe/Moscow') # use your local timezone name here # NOTE: pytz.reference.LocalTimezone() would produce wrong result here ## You could use `tzlocal` module to get local timezone on Unix and Win32 # from tzlocal import get_localzone # $ pip install tzlocal # # get local timezone # local_tz = get_localzone() def utc_to_local(utc_dt): local_dt = utc_dt.replace(tzinfo=pytz.utc).astim...

Convert ZonedDateTime To LocalDateTime At Time Zone

Answer : How can I convert it to LocalDateTime at time zone of Switzerland? You can convert the UTC ZonedDateTime into a ZonedDateTime with the time zone of Switzerland, but maintaining the same instant in time, and then get the LocalDateTime out of that, if you need to. I'd be tempted to keep it as a ZonedDateTime unless you need it as a LocalDateTime for some other reason though. ZonedDateTime utcZoned = ZonedDateTime.of(LocalDate.now().atTime(11, 30), ZoneOffset.UTC); ZoneId swissZone = ZoneId.of("Europe/Zurich"); ZonedDateTime swissZoned = utcZoned.withZoneSameInstant(swissZone); LocalDateTime swissLocal = swissZoned.toLocalDateTime(); It helps to understand the difference between LocalDateTime and ZonedDateTime. What you really want is a ZonedDateTime . If you wanted to remove the timezone from the string representation, you would convert it to a LocalDateTime . What you're looking for is: ZonedDateTime swissZonedDateTime = withZoneSameInstant(ZoneId.of...