我要向表单传递两个朴素的日期。然后使用pytz确保时区设置为EST。但是,这会导致错误。我猜这是由于DST问题引起的。日期和夏令时令人困惑。有人可以启发我如何制作“ DST证明”吗?
from rest_framework import serializers
from datetime import datetime
import pytz
class SearchForm(serializers.Serializer):
start_date = serializers.DateField(required=True)
end_date = serializers.DateField(required=False)
def save(self):
# Doesn't actually save,
start_date = self.validated_data['start_date']
end_date = self.validated_data['end_date']
# Convert dates to EST timezone
est = pytz.timezone('America/New_York')
start_date = datetime.combine(start_date, time.min).astimezone(est)
end_date = datetime.combine(end_date, time.max).astimezone(est)
print(f'Start date: {start_date} => {start_date.tzinfo}')
print(f'End date: {end_date} => {end_date.tzinfo}')
assert start_date.tzinfo == end_date.tzinfo
# Filter based on timeframe
qs = self.filter_timeframe(qs, start_date, end_date)
return SearchSerializer(qs, many=True)
将start_date
传递为“ 2018-11-1”,将end_date
传递为“ 2018-11-5”将得到AssertionError
。打印日期将导致:
Start date: 2018-11-01 00:00:00-04:00 => America/New_York
End date: 2018-11-05 23:59:59.999999-05:00 => America/New_York
问题是为什么end_date
时区-05:00
而不是-04:00
像start_date
一样?
答案 0 :(得分:2)
America / New_York与EST不同。前者根据夏令时调整。后者固定为东部标准时间。 使用:
est = pytz.timezone('EST')