简体   繁体   English

将特定时区中的datetime对象转换为该时区中的纪元秒

[英]Convert datetime object in a particular timezone to epoch seconds in that timezone

eg: 例如:

>>> print dt
2012-12-04 19:00:00-05:00

As you can see, I have this datetime object How can I convert this datetime object to epoch seconds in GMT -5. 如您所见,我有这个日期时间对象如何将此日期时间对象转换为GMT -5中的纪元秒。

How do I do this? 我该怎么做呢?

Your datetime is not a naive datetime, it knows about the timezone it's in (your print states that is -5). 你的日期时间不是一个天真的日期时间,它知道它所在的时区(你的打印状态是-5)。 So you just need to set it as utc before you convert it to epoch 因此,在将其转换为纪元之前,您只需将其设置为utc即可

>>> import time, pytz
>>> utc = pytz.timezone('UTC')
>>> utc_dt = utc.normalize(dt.astimezone(utc))
>>> time.mktime(utc_dt.timetuple())
1355270789.0 # This is just to show the format it outputs

If the dt object was a naive datetime object, you'd need to work with time zones to comply to daylight saving time while finding the correct hours between GMT 0. For example, Romania in the winter, it has +2 and in the summer +3. 如果dt对象是一个天真的日期时间对象,你需要使用时区来遵守夏令时,同时在GMT 0之间找到正确的小时数。例如,罗马尼亚在冬天,它有+2,在夏天+3。

For your -5 example, New-York will do: 对于你的-5例子,纽约将做:

>>> import time,pytz
>>> timezone = pytz.timezone('America/New_York')
>>> local_dt = timezone.localize(dt)

Now you have a non-naive datetime and you can get the epoch time like I first explained. 现在你有一个非天真的日期时间,你可以像我第一次解释的那样得到纪元时间。 Have fun 玩得开心

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM