I have tried two different scenarios:
- I fetched Current Datetime of
UTC
andEurope/Paris
and then I just converted in string which shows02 hours
of gap which is correct.
from datetime import datetime
import datetime as dt
import pytz
from dateutil import tz
current_utc = datetime.utcnow()
current_europe = datetime.now(pytz.timezone('Europe/Paris'))
current_utc_str = datetime.strftime(current_utc, "%Y-%m-%d %H:%M")
current_europe_str = datetime.strftime(current_europe, "%Y-%m-%d %H:%M")
print('current_utc',current_utc_str)
print('current_europe',current_europe_str)
results:
current_utc 2023-03-30 07:01
current_europe 2023-03-30 09:01
- I created a custom UTC datetime object and then converted it to Europe/Paris timezone and here are the results with the Gap of
01 Hour
.
from datetime import datetime
import datetime as dt
import pytz
from dateutil import tz
utc = datetime(2023, 3, 21, 23, 45).replace(tzinfo=dt.timezone.utc)
utc_str = datetime.strftime(utc, "%Y-%m-%d %H:%M")
print("utc_str", utc_str)
from_zone = tz.gettz("UTC")
to_zone = tz.gettz('Europe/Paris')
utc = utc.replace(tzinfo=from_zone)
new_time = utc.astimezone(to_zone)
new_time_str = datetime.strftime(new_time, "%Y-%m-%d %H:%M")
print("new_time_str", new_time_str)
results:
utc_str 2023-03-21 23:45
new_time_str 2023-03-22 00:45
What is the reason behind this 01 hour of variation
while fetching current and creating custom datetime?
Edit How can we handle Daylight Saving Time (DST) for custom created Datetime objects?
I think Display the time in a different time zone this doesn't answer about handling Daylight Saving Time (DST).