adding hours depending if date in DST

Viewed 33

From external API I'm getting this date as string '2021-03-31 21:00:00'. API returns it as UTC.

The goal is to add in summer 2 hours and in winter 3 hours.

1.

Is there some library that solves this problem?

  1. if not, then I should probably calculate myself if today is a day in DST and add 3 hours and if not add 2? if so how can i do it
1 Answers

You can use pytz for it if it is for a timezone with daylight savings which I'm assuming it is:

import datetime
import pytz


def convert_timezone(time_string: str, timezone_string: str):
    return pytz.UTC.localize(
        datetime.datetime.strptime(
            time_string,
            '%Y-%m-%d %H:%M:%S'
        )).astimezone(pytz.timezone(timezone_string))


# Non Daylight saving
print(convert_timezone('2021-02-28 21:00:00', 'utc'))
print(convert_timezone('2021-02-28 21:00:00', 'Europe/London'))
print(convert_timezone('2021-02-28 21:00:00', 'Europe/Paris'))
# Daylight saving
print(convert_timezone('2021-07-31 21:00:00', 'utc'))
print(convert_timezone('2021-07-31 21:00:00', 'Europe/London'))
print(convert_timezone('2021-07-31 21:00:00', 'Europe/Paris'))
# Dont-use daylight saving
print(convert_timezone('2021-02-28 21:00:00', 'Atlantic/Cape_Verde'))
print(convert_timezone('2021-07-31 21:00:00', 'Atlantic/Cape_Verde'))

outputs:

2021-02-28 21:00:00+00:00
2021-02-28 21:00:00+00:00
2021-02-28 22:00:00+01:00
2021-07-31 21:00:00+00:00
2021-07-31 22:00:00+01:00
2021-07-31 23:00:00+02:00
2021-02-28 20:00:00-01:00
2021-07-31 20:00:00-01:00

Just use it with your timezone and treat the return value as you would any datetime.datetime object. e.g.

print(convert_timezone('2021-07-31 21:00:00', 'Europe/Paris').strftime("%m/%d/%Y, %H:%M"))

outputs as a string:

07/31/2021, 23:00
Related