简体   繁体   English

Python将UTC转换为PST / PDT格式

[英]Python Convert UTC to PST / PDT format

I have a web app that captures date / time via a JS script and calculates seconds since epoch in UTC format - ex 134250270000. In the backend we have a Python script that fetches data from DB but has date / time stored in number of seconds since epoch in PST format. 我有一个Web应用程序,该应用程序通过JS脚本捕获日期/时间并以UTC格式计算自纪元以来的秒数-ex134250270000。在后端,我们有一个Python脚本,该脚本可从数据库中获取数据,但日期/时间以秒为单位存储PST格式的纪元。 There is always a difference of seconds between UTC and PST if counted from epoch. 如果从纪元算起,UTC和PST之间总是存在秒差。

Is there any method by which I can convert the UTC seconds since to epoch to PST seconds since epoch? 有什么方法可以将自时间段以来的UTC秒转换为自时间段以来的PST秒? We need to take a note of daylight changes in PST timezone also? 我们还需要记录PST时区的日光变化吗?

EDIT:: 编辑::

I have the seconds since epoch in UTC format:

1342502700

I found that I get the sum in seconds between UTC and local standard time via:

>>> time.timezone / 3600
8

So If I add 1342502700 to time.timezone:

>>> print 1342502700 + time.timezone
1344153600

Will it always give me PDT / PST times correctly? 它会始终为我提供正确的PDT / PST时间吗?

EDIT:: 编辑::

Maybe this is the correct one: 也许这是正确的:

>>> import time
>>> offset = time.timezone if (time.daylight == 0) else time.altzone
>>> offset / 60 / 60
7

time.daylight will be non-zero if daylight savings is currently in effect. 如果当前实行夏令时,则time.daylight将不为零。

I think somewhere in your conversions there's an implied time zone that's messing things up. 我认为您转换中的某个地方存在一个隐含的时区,使事情变得混乱。 Regardless, I think what you're looking for is time.altzone : 无论如何,我认为您正在寻找的是time.altzone

>>> from time import *
>>> ctime(time())
'Mon Aug 13 16:54:02 2012'
>>> ctime(time()+altzone)
'Mon Aug 13 08:54:04 2012'

I'm on Taipei time right now, so my local time (the first one) is later than UTC. 我现在在台北时间,所以我的当地时间(第一个)比UTC晚。

EDIT: I missed the line in the documentation that says only to use altzone if daylight is non-zero. 编辑:我错过了文档中仅说如果daylight不为零时使用altzone的行。 Apparently it's a bit more complicated than I thought if you live somewhere with Daylight Savings Time. 显然,如果您住在“夏令时”,这比我想的要复杂。 Refer to this post if you need to deal with that: 如果您需要处理此问题,请参考这篇文章:

Python: get timezone based on DST for a timestamp Python:获取基于DST的时区作为时间戳

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

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