在Python中获取计算机的UTC偏移量

发布于 2024-09-07 20:20:02 字数 35 浏览 3 评论 0 原文

在Python中,如何找到计算机设置的UTC时间偏移量?

In Python, how do you find what UTC time offset the computer is set to?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

美羊羊 2024-09-14 20:20:02

time.timezone

import time

print -time.timezone

它以秒为单位打印 UTC 偏移量(以考虑帐户夏令时 (DST) 请参阅 time.altzone

is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (time.altzone if is_dst else time.timezone)

其中 utc offset 是通过以下方式定义的:“要获取本地时间,请将 utc 偏移量添加到 utc 时间。”

在 Python 3.3+ 中,有 tm_gmtoff 属性(如果底层 C 库支持):

utc_offset = time.localtime().tm_gmtoff

注意:time.daylight 可能会在 一些边缘情况

如果 datetime 在 Python 3.3+ 上可用,则会自动使用 tm_gmtoff。 :

from datetime import datetime, timedelta, timezone

d = datetime.now(timezone.utc).astimezone()
utc_offset = d.utcoffset() // timedelta(seconds=1)

要以解决 time.daylight 问题并且即使 tm_gmtoff 不可用也能工作的方式获取当前 UTC 偏移量,@jts 的建议可用于子化本地和 UTC 时间:

import time
from datetime import datetime

ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
              datetime.utcfromtimestamp(ts)).total_seconds()

要获取过去/未来日期的 UTC 偏移量,pytz / zoneinfo 可以使用时区:

from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal

tz = get_localzone() # local timezone 
d = datetime.now(tz) # or some other local date 
utc_offset = d.utcoffset().total_seconds()

它在 DST 转换期间工作,它适用于过去/未来的日期,即使本地时区当时具有不同的 UTC 偏移量,例如,2010-2015 年期间的欧洲/莫斯科时区。

time.timezone:

import time

print -time.timezone

It prints UTC offset in seconds (to take into account Daylight Saving Time (DST) see time.altzone:

is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (time.altzone if is_dst else time.timezone)

where utc offset is defined via: "To get local time, add utc offset to utc time."

In Python 3.3+ there is tm_gmtoff attribute if underlying C library supports it:

utc_offset = time.localtime().tm_gmtoff

Note: time.daylight may give a wrong result in some edge cases.

tm_gmtoff is used automatically by datetime if it is available on Python 3.3+:

from datetime import datetime, timedelta, timezone

d = datetime.now(timezone.utc).astimezone()
utc_offset = d.utcoffset() // timedelta(seconds=1)

To get the current UTC offset in a way that workarounds the time.daylight issue and that works even if tm_gmtoff is not available, @jts's suggestion to substruct the local and UTC time can be used:

import time
from datetime import datetime

ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
              datetime.utcfromtimestamp(ts)).total_seconds()

To get UTC offset for past/future dates, pytz / zoneinfo timezones could be used:

from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal

tz = get_localzone() # local timezone 
d = datetime.now(tz) # or some other local date 
utc_offset = d.utcoffset().total_seconds()

It works during DST transitions, it works for past/future dates even if the local timezone had different UTC offset at the time e.g., Europe/Moscow timezone in 2010-2015 period.

许久 2024-09-14 20:20:02

gmtime() 将返回 UTC 时间,localtime() 将返回本地时间,因此减去两者应该得到 utc 偏移量。

来自 https://pubs.opengroup.org/onlinepubs/009695399/functions/gmtime .html

gmtime() 函数应将计时器指向的纪元以来的时间(以秒为单位)转换为细分时间,表示为协调世界时 (UTC)。

因此,尽管名称为 gmttime,该函数仍返回 UTC。

gmtime() will return the UTC time and localtime() will return the local time so subtracting the two should give you the utc offset.

From https://pubs.opengroup.org/onlinepubs/009695399/functions/gmtime.html

The gmtime() function shall convert the time in seconds since the Epoch pointed to by timer into a broken-down time, expressed as Coordinated Universal Time (UTC).

So, despite the name gmttime, the function returns UTC.

清眉祭 2024-09-14 20:20:02

我喜欢:

>>> strftime('%z')
'-0700'

我先尝试了 JTS 的答案,但它给了我错误的结果。我现在在-0700,但它说我在-0800。但我必须先进行一些转换才能得到可以减去的东西,所以也许答案不完整而不是错误。

I like:

>>> strftime('%z')
'-0700'

I tried JTS' answer first, but it gave me the wrong result. I'm in -0700 now, but it was saying I was in -0800. But I had to do some conversion before I could get something I could subtract, so maybe the answer was more incomplete than incorrect.

怎会甘心 2024-09-14 20:20:02

时间模块 有一个时区偏移量,以“西西秒数”为单位的整数世界标准时间”

import time
time.timezone

the time module has a timezone offset, given as an integer in "seconds west of UTC"

import time
time.timezone
零度℉ 2024-09-14 20:20:02

您可以使用 datetimedateutil 库来获取 timedelta 对象:

>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>>
>>> # From a datetime object
>>> current_time = datetime.now(tzlocal())
>>> current_time.utcoffset()
datetime.timedelta(seconds=7200)
>>> current_time.dst()
datetime.timedelta(seconds=3600)
>>>
>>> # From a tzlocal object
>>> time_zone = tzlocal()
>>> time_zone.utcoffset(datetime.now())
datetime.timedelta(seconds=7200)
>>> time_zone.dst(datetime.now())
datetime.timedelta(seconds=3600)
>>>
>>> print('Your UTC offset is {:+g}'.format(current_time.utcoffset().total_seconds()/3600))
Your UTC offset is +2

You can use the datetime and dateutil libraries to get the offset as a timedelta object:

>>> from datetime import datetime
>>> from dateutil.tz import tzlocal
>>>
>>> # From a datetime object
>>> current_time = datetime.now(tzlocal())
>>> current_time.utcoffset()
datetime.timedelta(seconds=7200)
>>> current_time.dst()
datetime.timedelta(seconds=3600)
>>>
>>> # From a tzlocal object
>>> time_zone = tzlocal()
>>> time_zone.utcoffset(datetime.now())
datetime.timedelta(seconds=7200)
>>> time_zone.dst(datetime.now())
datetime.timedelta(seconds=3600)
>>>
>>> print('Your UTC offset is {:+g}'.format(current_time.utcoffset().total_seconds()/3600))
Your UTC offset is +2
杯别 2024-09-14 20:20:02
hours_delta = (time.mktime(time.localtime()) - time.mktime(time.gmtime())) / 60 / 60
hours_delta = (time.mktime(time.localtime()) - time.mktime(time.gmtime())) / 60 / 60
夜深人未静 2024-09-14 20:20:02

使用 UTC 校正时区创建 Unix 时间戳

这个简单的函数将使您轻松从 MySQL/PostgreSQL 数据库 date 对象获取当前时间。

def timestamp(date='2018-05-01'):
    return int(time.mktime(
        datetime.datetime.strptime( date, "%Y-%m-%d" ).timetuple()
    )) + int(time.strftime('%z')) * 6 * 6

示例输出

>>> timestamp('2018-05-01')
1525132800
>>> timestamp('2018-06-01')
1527811200

Create a Unix Timestamp with UTC Corrected Timezone

This simple function will make it easy for you to get the current time from a MySQL/PostgreSQL database date object.

def timestamp(date='2018-05-01'):
    return int(time.mktime(
        datetime.datetime.strptime( date, "%Y-%m-%d" ).timetuple()
    )) + int(time.strftime('%z')) * 6 * 6

Example Output

>>> timestamp('2018-05-01')
1525132800
>>> timestamp('2018-06-01')
1527811200
各自安好 2024-09-14 20:20:02

对我来说这个技巧是做什么的:

timezone_offset = (datetime.now(tz(DESIRED_TIMEZONE)).utcoffset().total_seconds()) / 3600

这样,我能够获得任意时区utc偏移,而不仅仅是机器的时区(可以是虚拟机)时区配置错误)

What did the trick for me was doing:

timezone_offset = (datetime.now(tz(DESIRED_TIMEZONE)).utcoffset().total_seconds()) / 3600

This way, I'm able to get the utc offset of an arbitrary timezone not only the machine's timezone(which can be a VM with a misconfigured timezone)

陌上芳菲 2024-09-14 20:20:02

这是一些仅导入日期时间和时间的 python3 代码。华泰

>>> from datetime import datetime
>>> import time
>>> def date2iso(thedate):
...     strdate = thedate.strftime("%Y-%m-%dT%H:%M:%S")
...     minute = (time.localtime().tm_gmtoff / 60) % 60
...     hour = ((time.localtime().tm_gmtoff / 60) - minute) / 60
...     utcoffset = "%.2d%.2d" %(hour, minute)
...     if utcoffset[0] != '-':
...         utcoffset = '+' + utcoffset
...     return strdate + utcoffset
... 
>>> date2iso(datetime.fromtimestamp(time.time()))
'2015-04-06T23:56:30-0400'

Here is some python3 code with just datetime and time as imports. HTH

>>> from datetime import datetime
>>> import time
>>> def date2iso(thedate):
...     strdate = thedate.strftime("%Y-%m-%dT%H:%M:%S")
...     minute = (time.localtime().tm_gmtoff / 60) % 60
...     hour = ((time.localtime().tm_gmtoff / 60) - minute) / 60
...     utcoffset = "%.2d%.2d" %(hour, minute)
...     if utcoffset[0] != '-':
...         utcoffset = '+' + utcoffset
...     return strdate + utcoffset
... 
>>> date2iso(datetime.fromtimestamp(time.time()))
'2015-04-06T23:56:30-0400'
梦途 2024-09-14 20:20:02

这对我有用:

if time.daylight > 0:
        return time.altzone
    else:
        return time.timezone

This works for me:

if time.daylight > 0:
        return time.altzone
    else:
        return time.timezone
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文