DST timezone issue in django app

2019-07-20 03:44发布

I am making an events app in django.

In that I need to make a copy of one event object (row/entry in DB) into another. It creates another object with same details.

This event object involves timezone and Day light Saving.

I am facing problems during DST. I have applied time delta of 5 days during copying of objects.


In normal days

Event object 1 date: Nov. 10, 2014 10:36 a.m.

Event object 2(copy of 1) date: Nov. 15, 2014 10:36 a.m.

This OK..!


But in DST days I don't want this 1 hr change.

Event object 1 date: Oct. 30, 2015, 10:36 a.m.

Event object 2(copy of 1) date: Nov. 4, 2015, 9:36 a.m.


Here 1 hour is automatically reducing in object 2 during DST change(Oct 30 is belongs to DST, Nov 4 is not). But I want same time. How can I fix this???

1条回答
不美不萌又怎样
2楼-- · 2019-07-20 04:30

Timedeltas algebra work by adding/substracting time, not dates, that's why you get one hour less when passing through a DST change.

I think the easiest solution is to perform the algebra using localized times and not normalizing. This way you will be "doing it wrong" but you'll get what you want.

Example:

timestamp_1 = event.timestamp   # we assume this datetime comes in UTC
madrid = pytz.timezone('Europe/Madrid')
madrid.localize(timestamp_1)
timestamp_2 = timestamp_1 + datetime.timedelta(days=5)
new_event = Event(timestamp=timestamp_2)

See http://pytz.sourceforge.net/#localized-times-and-date-arithmetic

查看更多
登录 后发表回答