如何将本地时间字符串转换为 UTC?

发布于 2024-07-05 22:40:40 字数 465 浏览 12 评论 0原文

如何将日期时间本地时间字符串转换为UTC时间字符串

我确信我以前做过这个,但找不到它,所以希望将来能帮助我(和其他人)做到这一点。

说明:例如,如果我的本地时区 (+10) 为 2008-09-17 14:02:00,我'我想生成一个具有等效 UTC 时间的字符串:2008-09-17 04:02:00

另外,来自 http://lucumr.pocoo.org/2011/7 /15/eppur-si-muove/,请注意,一般来说这是不可能的,因为 DST 和其他问题没有从本地时间到 UTC 时间的唯一转换。

How do I convert a datetime string in local time to a string in UTC time?

I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.

Clarification: For example, if I have 2008-09-17 14:02:00 in my local timezone (+10), I'd like to generate a string with the equivalent UTC time: 2008-09-17 04:02:00.

Also, from http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.

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

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

发布评论

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

评论(26

甚是思念 2024-07-12 22:40:40

默认的 datetime 对象不会设置时区(tzinfo 属性将为 None),因此在将字符串解析为 datetime 对象后,时区应转换为 UTC:

from datetime import datetime, timezone

def convert_local_time_to_utc(dt: str, format="%Y-%m-%d %H:%M:%S.%f"):
    dt = datetime.strptime(dt, format).astimezone(tz=timezone.utc)
    return dt

local_datetime_string = "2021-01-01 01:23:45.678910"
utc_datetime = convert_local_time_to_utc(dt=local_datetime_string)
print(utc_datetime.strftime("%Y-%m-%d %H:%M:%S.%f"))
# 2020-12-31 19:23:45.678910

The default datetime object will have no timezone set up (tzinfo property will be None), so after parsing the string into the datetime object, the timezone should be convert to UTC:

from datetime import datetime, timezone

def convert_local_time_to_utc(dt: str, format="%Y-%m-%d %H:%M:%S.%f"):
    dt = datetime.strptime(dt, format).astimezone(tz=timezone.utc)
    return dt

local_datetime_string = "2021-01-01 01:23:45.678910"
utc_datetime = convert_local_time_to_utc(dt=local_datetime_string)
print(utc_datetime.strftime("%Y-%m-%d %H:%M:%S.%f"))
# 2020-12-31 19:23:45.678910
淡淡绿茶香 2024-07-12 22:40:40

如果您已经有一个日期时间对象 my_dt,您可以将其更改为 UTC:

datetime.datetime.utcfromtimestamp(my_dt.timestamp())

If you already have a datetime object my_dt you can change it to UTC with:

datetime.datetime.utcfromtimestamp(my_dt.timestamp())
美男兮 2024-07-12 22:40:40

简单地说,将任何datetime日期转换为UTC时间:

from datetime import datetime

def to_utc(date):
    return datetime(*date.utctimetuple()[:6])

让我们用一个例子来解释。 首先,我们需要从字符串创建一个 datetime

>>> date = datetime.strptime("11 Feb 2011 17:33:54 -0800", "%d %b %Y %H:%M:%S %z")

然后,我们可以调用该函数:

>>> to_utc(date)
datetime.datetime(2011, 2, 12, 1, 33, 54)

逐步了解该函数的工作原理:

>>> date.utctimetuple()
time.struct_time(tm_year=2011, tm_mon=2, tm_mday=12, tm_hour=1, tm_min=33, tm_sec=54, tm_wday=5, tm_yday=43, tm_isdst=0)
>>> date.utctimetuple()[:6]
(2011, 2, 12, 1, 33, 54)
>>> datetime(*date.utctimetuple()[:6])
datetime.datetime(2011, 2, 12, 1, 33, 54)

Briefly, to convert any datetime date to UTC time:

from datetime import datetime

def to_utc(date):
    return datetime(*date.utctimetuple()[:6])

Let's explain with an example. First, we need to create a datetime from the string:

>>> date = datetime.strptime("11 Feb 2011 17:33:54 -0800", "%d %b %Y %H:%M:%S %z")

Then, we can call the function:

>>> to_utc(date)
datetime.datetime(2011, 2, 12, 1, 33, 54)

Step by step how the function works:

>>> date.utctimetuple()
time.struct_time(tm_year=2011, tm_mon=2, tm_mday=12, tm_hour=1, tm_min=33, tm_sec=54, tm_wday=5, tm_yday=43, tm_isdst=0)
>>> date.utctimetuple()[:6]
(2011, 2, 12, 1, 33, 54)
>>> datetime(*date.utctimetuple()[:6])
datetime.datetime(2011, 2, 12, 1, 33, 54)
月下客 2024-07-12 22:40:40

在 python3 中:

pip install python-dateutil

from dateutil.parser import tz

mydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None) 

In python3:

pip install python-dateutil

from dateutil.parser import tz

mydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None) 
一抹微笑 2024-07-12 22:40:40

怎么样 -

time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))

如果秒是 None 那么它将本地时间转换为 UTC 时间,否则将传递的时间转换为 UTC。

How about -

time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))

if seconds is None then it converts the local time to UTC time else converts the passed in time to UTC.

一个人的夜不怕黑 2024-07-12 22:40:40

首先,将字符串解析为一个简单的日期时间对象。 这是一个没有附加时区信息的 datetime.datetime 实例。 请参阅其文档

使用 pytz 模块,该模块附带完整的时区列表 + UTC。 找出本地时区是什么,从中构造一个时区对象,然后操作它并将其附加到原始日期时间。

最后,使用 datetime.astimezone() 方法将日期时间转换为 UTC。

源代码,使用本地时区“America/Los_Angeles”,对于字符串“2001-2-3 10:11:12”:

from datetime import datetime   
import pytz

local = pytz.timezone("America/Los_Angeles")
naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)

从那里,您可以使用 strftime() 方法来格式化 UTC根据需要的日期时间:

utc_dt.strftime("%Y-%m-%d %H:%M:%S")

First, parse the string into a naive datetime object. This is an instance of datetime.datetime with no attached timezone information. See its documentation.

Use the pytz module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.

Finally, use datetime.astimezone() method to convert the datetime to UTC.

Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":

from datetime import datetime   
import pytz

local = pytz.timezone("America/Los_Angeles")
naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)

From there, you can use the strftime() method to format the UTC datetime as needed:

utc_dt.strftime("%Y-%m-%d %H:%M:%S")
她说她爱他 2024-07-12 22:40:40

注意 - 从 2020 年起,您不应使用 .utcnow().utcfromtimestamp(xxx)。 由于您可能已经转向 python3,因此您应该使用时区感知的日期时间对象。

>>> from datetime import timezone
>>> 
>>> # alternative to '.utcnow()'
>>> dt_now = datetime.datetime.now(datetime.timezone.utc)
>>>
>>> # alternative to '.utcfromtimestamp()'
>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)

详情请参阅:https://blog.ganssle.io/articles/2019/11 /utcnow.html

原始答案(从 2010 年开始):

datetime 模块的 utcnow()函数可用于获取当前UTC时间。

>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2010-02-01 06:59:19'

正如汤姆上面提到的链接:http://lucumr.pocoo。 org/2011/7/15/eppur-si-muove/ 说:

UTC 是一个没有夏令时的时区,但仍然是一个时区
过去没有进行配置更改。

始终以 UTC 格式测量和存储时间

如果您需要记录时间的拍摄地点,请将其单独存储。
不要存储当地时间+时区信息!

注意 - 如果您的任何数据位于使用 DST 的地区,请使用 pytz 并看看 John Millikin 的回答。

如果您想从给定字符串获取 UTC 时间,并且您很幸运地位于世界上不使用 DST 的地区,或者您拥有的数据仅与 UTC 存在偏移而未应用 DST:

-- > 使用当地时间作为偏移值的基础:

>>> # Obtain the UTC Offset for the current system:
>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
>>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")
>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'

--> 或者,从已知的偏移量开始,使用 datetime.timedelta():

>>> UTC_OFFSET = 10
>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'

更新:

由于 python 3.2 datetime.timezone 可用。 您可以使用以下命令生成时区感知日期时间对象:

import datetime

timezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)

如果您准备好进行时区转换,请阅读以下内容:

https://medium.com/@eleroy/10-things-you-需要了解 python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7 中的日期和时间

NOTE -- As of 2020 you should not be using .utcnow() or .utcfromtimestamp(xxx). As you've presumably moved on to python3,you should be using timezone aware datetime objects.

>>> from datetime import timezone
>>> 
>>> # alternative to '.utcnow()'
>>> dt_now = datetime.datetime.now(datetime.timezone.utc)
>>>
>>> # alternative to '.utcfromtimestamp()'
>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)

For details see: https://blog.ganssle.io/articles/2019/11/utcnow.html

original answer (from 2010):

The datetime module's utcnow() function can be used to obtain the current UTC time.

>>> import datetime
>>> utc_datetime = datetime.datetime.utcnow()
>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2010-02-01 06:59:19'

As the link mentioned above by Tom: http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/ says:

UTC is a timezone without daylight saving time and still a timezone
without configuration changes in the past.

Always measure and store time in UTC.

If you need to record where the time was taken, store that separately.
Do not store the local time + timezone information!

NOTE - If any of your data is in a region that uses DST, use pytz and take a look at John Millikin's answer.

If you want to obtain the UTC time from a given string and you're lucky enough to be in a region in the world that either doesn't use DST, or you have data that is only offset from UTC without DST applied:

--> using local time as the basis for the offset value:

>>> # Obtain the UTC Offset for the current system:
>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()
>>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")
>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'

--> Or, from a known offset, using datetime.timedelta():

>>> UTC_OFFSET = 10
>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)
>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")
'2008-09-17 04:04:00'

UPDATE:

Since python 3.2 datetime.timezone is available. You can generate a timezone aware datetime object with the command below:

import datetime

timezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)

If your ready to take on timezone conversions go read this:

https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7

机场等船 2024-07-12 22:40:40

谢谢@rofly,从字符串到字符串的完整转换如下:

import time
time.strftime("%Y-%m-%d %H:%M:%S", 
              time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00", 
                                                    "%Y-%m-%d %H:%M:%S"))))

我对 time/calendar 函数的总结:

time.strptime
字符串 --> 元组(未应用时区,因此匹配字符串)

time.mktime
本地时间元组 --> 自纪元以来的秒数(始终为当地时间)

time.gmtime
自纪元以来的秒数 --> UTC

calendar.timegm
中的元组
UTC 元组 --> 自纪元以来的秒数

time.localtime
自纪元以来的秒数 --> 本地时区的元组

Thanks @rofly, the full conversion from string to string is as follows:

import time
time.strftime("%Y-%m-%d %H:%M:%S", 
              time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00", 
                                                    "%Y-%m-%d %H:%M:%S"))))

My summary of the time/calendar functions:

time.strptime
string --> tuple (no timezone applied, so matches string)

time.mktime
local time tuple --> seconds since epoch (always local time)

time.gmtime
seconds since epoch --> tuple in UTC

and

calendar.timegm
tuple in UTC --> seconds since epoch

time.localtime
seconds since epoch --> tuple in local timezone

撩发小公举 2024-07-12 22:40:40

对于任何对最高票数答案感到困惑的人。 您可以通过生成日期时间对象将日期时间字符串转换为 python 中的 utc 时间,然后可以使用 astimezone(pytz.utc) 获取 utc 中的日期时间。

例如。

假设我们有 isoformat 格式的本地日期时间字符串 2021-09-02T19:02:00Z

现在将此字符串转换为 utc 日期时间。 使用此字符串生成 datetime 对象,

我们首先需要通过dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')

这将为您提供 python datetime 对象,那么您可以使用 astimezone(pytz.utc) 获取 utc 日期时间,例如

dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M :%SZ') dt = dt.astimezone(pytz.utc)

这将为您提供 utc 格式的日期时间对象,然后您可以使用 dt.strftime("%Y-%m- %d %H:%M:%S")

完整代码,例如:

from datetime import datetime
import pytz

def converLocalToUTC(datetime, getString=True, format="%Y-%m-%d %H:%M:%S"):
    dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')
    dt = dt.astimezone(pytz.utc)
    
    if getString:
        return dt.strftime(format)
    return dt

然后您可以将其称为

converLocalToUTC("2021-09-02T19:02:00Z")

获得帮助
https://stackoverflow.com/a/79877/7756843

For anyone who is confused with the most upvoted answer. You can convert a datetime string to utc time in python by generating a datetime object and then you can use astimezone(pytz.utc) to get datetime in utc.

For eg.

let say we have local datetime string as 2021-09-02T19:02:00Z in isoformat

Now to convert this string to utc datetime. we first need to generate datetime object using this string by

dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')

this will give you python datetime object, then you can use astimezone(pytz.utc) to get utc datetime like

dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ') dt = dt.astimezone(pytz.utc)

this will give you datetime object in utc, then you can convert it to string using dt.strftime("%Y-%m-%d %H:%M:%S")

full code eg:

from datetime import datetime
import pytz

def converLocalToUTC(datetime, getString=True, format="%Y-%m-%d %H:%M:%S"):
    dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')
    dt = dt.astimezone(pytz.utc)
    
    if getString:
        return dt.strftime(format)
    return dt

then you can call it as

converLocalToUTC("2021-09-02T19:02:00Z")

took help from
https://stackoverflow.com/a/79877/7756843

临风闻羌笛 2024-07-12 22:40:40

我在此处找到了另一个问题的最佳答案。 它只使用 python 内置库,不需要您输入本地时区(在我的情况下是一个要求)

import time
import calendar

local_time = time.strptime("2018-12-13T09:32:00.000", "%Y-%m-%dT%H:%M:%S.%f")
local_seconds = time.mktime(local_time)
utc_time = time.gmtime(local_seconds)

我在这里重新发布答案,因为这个问题会在谷歌中弹出,而不是根据搜索关键字弹出的链接问题。

I found the best answer on another question here. It only uses python built-in libraries and does not require you to input your local timezone (a requirement in my case)

import time
import calendar

local_time = time.strptime("2018-12-13T09:32:00.000", "%Y-%m-%dT%H:%M:%S.%f")
local_seconds = time.mktime(local_time)
utc_time = time.gmtime(local_seconds)

I'm reposting the answer here since this question pops up in google instead of the linked question depending on the search keywords.

我家小可爱 2024-07-12 22:40:40

我的一个项目中有这样的代码:

from datetime import datetime
## datetime.timezone works in newer versions of python
try:
    from datetime import timezone
    utc_tz = timezone.utc
except:
    import pytz
    utc_tz = pytz.utc

def _to_utc_date_string(ts):
    # type (Union[date,datetime]]) -> str
    """coerce datetimes to UTC (assume localtime if nothing is given)"""
    if (isinstance(ts, datetime)):
        try:
            ## in python 3.6 and higher, ts.astimezone() will assume a
            ## naive timestamp is localtime (and so do we)
            ts = ts.astimezone(utc_tz)
        except:
            ## in python 2.7 and 3.5, ts.astimezone() will fail on
            ## naive timestamps, but we'd like to assume they are
            ## localtime
            import tzlocal
            ts = tzlocal.get_localzone().localize(ts).astimezone(utc_tz)
    return ts.strftime("%Y%m%dT%H%M%SZ")

I have this code in one of my projects:

from datetime import datetime
## datetime.timezone works in newer versions of python
try:
    from datetime import timezone
    utc_tz = timezone.utc
except:
    import pytz
    utc_tz = pytz.utc

def _to_utc_date_string(ts):
    # type (Union[date,datetime]]) -> str
    """coerce datetimes to UTC (assume localtime if nothing is given)"""
    if (isinstance(ts, datetime)):
        try:
            ## in python 3.6 and higher, ts.astimezone() will assume a
            ## naive timestamp is localtime (and so do we)
            ts = ts.astimezone(utc_tz)
        except:
            ## in python 2.7 and 3.5, ts.astimezone() will fail on
            ## naive timestamps, but we'd like to assume they are
            ## localtime
            import tzlocal
            ts = tzlocal.get_localzone().localize(ts).astimezone(utc_tz)
    return ts.strftime("%Y%m%dT%H%M%SZ")
明媚如初 2024-07-12 22:40:40

使用 http://crsmithdev.com/arrow/

arrowObj = arrow.Arrow.strptime('2017-02-20 10:00:00', '%Y-%m-%d %H:%M:%S' , 'US/Eastern')

arrowObj.to('UTC') or arrowObj.to('local') 

这个库让生活变得轻松:)

Using http://crsmithdev.com/arrow/

arrowObj = arrow.Arrow.strptime('2017-02-20 10:00:00', '%Y-%m-%d %H:%M:%S' , 'US/Eastern')

arrowObj.to('UTC') or arrowObj.to('local') 

This library makes life easy :)

云淡月浅 2024-07-12 22:40:40

为了避开夏令时等。

上述答案都没有对我有特别帮助。 下面的代码适用于 GMT。

def get_utc_from_local(date_time, local_tz=None):
    assert date_time.__class__.__name__ == 'datetime'
    if local_tz is None:
        local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
    local_time = local_tz.normalize(local_tz.localize(date_time))
    return local_time.astimezone(pytz.utc)

import pytz
from datetime import datetime

summer_11_am = datetime(2011, 7, 1, 11)
get_utc_from_local(summer_11_am)
>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)

winter_11_am = datetime(2011, 11, 11, 11)
get_utc_from_local(winter_11_am)
>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)

For getting around day-light saving, etc.

None of the above answers particularly helped me. The code below works for GMT.

def get_utc_from_local(date_time, local_tz=None):
    assert date_time.__class__.__name__ == 'datetime'
    if local_tz is None:
        local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
    local_time = local_tz.normalize(local_tz.localize(date_time))
    return local_time.astimezone(pytz.utc)

import pytz
from datetime import datetime

summer_11_am = datetime(2011, 7, 1, 11)
get_utc_from_local(summer_11_am)
>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)

winter_11_am = datetime(2011, 11, 11, 11)
get_utc_from_local(winter_11_am)
>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)
临风闻羌笛 2024-07-12 22:40:40

在 python 3.9.0 中,将本地时间 local_time 解析为 datetime.datetime 对象后,只需使用 local_time.astimezone(datetime.timezone.utc)

In python 3.9.0, after you've parsed your local time local_time into datetime.datetime object, just use local_time.astimezone(datetime.timezone.utc).

擦肩而过的背影 2024-07-12 22:40:40

你可以这样做:

>>> from time import strftime, gmtime, localtime
>>> strftime('%H:%M:%S', gmtime()) #UTC time
>>> strftime('%H:%M:%S', localtime()) # localtime

You can do it with:

>>> from time import strftime, gmtime, localtime
>>> strftime('%H:%M:%S', gmtime()) #UTC time
>>> strftime('%H:%M:%S', localtime()) # localtime
动听の歌 2024-07-12 22:40:40

怎么样 -

time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))

如果秒是 None 那么它将本地时间转换为 UTC 时间,否则将传递的时间转换为 UTC。

How about -

time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))

if seconds is None then it converts the local time to UTC time else converts the passed in time to UTC.

昵称有卵用 2024-07-12 22:40:40

很简单

,我是这样实现的:

>>> utc_delta = datetime.utcnow()-datetime.now()
>>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta
>>> print(utc_time)
2008-09-17 19:01:59.999996

奇特的实现

如果你想变得奇特,你可以把它变成一个函子:

class to_utc():
    utc_delta = datetime.utcnow() - datetime.now()

    def __call__(cls, t):
        return t + cls.utc_delta

结果:

>>> utc_converter = to_utc()
>>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))
2008-09-17 19:01:59.999996

Simple

I did it like this:

>>> utc_delta = datetime.utcnow()-datetime.now()
>>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta
>>> print(utc_time)
2008-09-17 19:01:59.999996

Fancy Implementation

If you want to get fancy, you can turn this into a functor:

class to_utc():
    utc_delta = datetime.utcnow() - datetime.now()

    def __call__(cls, t):
        return t + cls.utc_delta

Result:

>>> utc_converter = to_utc()
>>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))
2008-09-17 19:01:59.999996
似狗非友 2024-07-12 22:40:40

如果您更喜欢 datetime.datetime:

dt = datetime.strptime("2008-09-17 14:04:00","%Y-%m-%d %H:%M:%S")
utc_struct_time = time.gmtime(time.mktime(dt.timetuple()))
utc_dt = datetime.fromtimestamp(time.mktime(utc_struct_time))
print dt.strftime("%Y-%m-%d %H:%M:%S")

if you prefer datetime.datetime:

dt = datetime.strptime("2008-09-17 14:04:00","%Y-%m-%d %H:%M:%S")
utc_struct_time = time.gmtime(time.mktime(dt.timetuple()))
utc_dt = datetime.fromtimestamp(time.mktime(utc_struct_time))
print dt.strftime("%Y-%m-%d %H:%M:%S")
梦里兽 2024-07-12 22:40:40
import time

import datetime

def Local2UTC(LocalTime):

    EpochSecond = time.mktime(LocalTime.timetuple())
    utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)

    return utcTime

>>> LocalTime = datetime.datetime.now()

>>> UTCTime = Local2UTC(LocalTime)

>>> LocalTime.ctime()

'Thu Feb  3 22:33:46 2011'

>>> UTCTime.ctime()

'Fri Feb  4 05:33:46 2011'
import time

import datetime

def Local2UTC(LocalTime):

    EpochSecond = time.mktime(LocalTime.timetuple())
    utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)

    return utcTime

>>> LocalTime = datetime.datetime.now()

>>> UTCTime = Local2UTC(LocalTime)

>>> LocalTime.ctime()

'Thu Feb  3 22:33:46 2011'

>>> UTCTime.ctime()

'Fri Feb  4 05:33:46 2011'
网名女生简单气质 2024-07-12 22:40:40

下面是 Python3.9zoneinfo 模块的示例strong>:

from datetime import datetime
from zoneinfo import ZoneInfo

# Get timezone we're trying to convert from
local_tz = ZoneInfo("America/New_York")
# UTC timezone
utc_tz = ZoneInfo("UTC")

dt = datetime.strptime("2021-09-20 17:20:00","%Y-%m-%d %H:%M:%S")
dt = dt.replace(tzinfo=local_tz)
dt_utc = dt.astimezone(utc_tz)

print(dt.strftime("%Y-%m-%d %H:%M:%S"))
print(dt_utc.strftime("%Y-%m-%d %H:%M:%S"))

在您要转换的时区不反映系统本地时区的情况下,这可能比仅使用 dt.astimezone() 更好。 不必依赖外部库也很好。

注意:这可能不适用于 Windows 系统,因为 zoneinfo 依赖于可能不存在的 IANA 数据库。 可以安装 tzdata 包作为解决方法。 它是第一方包,但不在标准库中。

Here's an example with the native zoneinfo module in Python3.9:

from datetime import datetime
from zoneinfo import ZoneInfo

# Get timezone we're trying to convert from
local_tz = ZoneInfo("America/New_York")
# UTC timezone
utc_tz = ZoneInfo("UTC")

dt = datetime.strptime("2021-09-20 17:20:00","%Y-%m-%d %H:%M:%S")
dt = dt.replace(tzinfo=local_tz)
dt_utc = dt.astimezone(utc_tz)

print(dt.strftime("%Y-%m-%d %H:%M:%S"))
print(dt_utc.strftime("%Y-%m-%d %H:%M:%S"))

This may be preferred over just using dt.astimezone() in situations where the timezone you're converting from isn't reflective of your system's local timezone. Not having to rely on external libraries is nice too.

Note: This may not work on Windows systems, since zoneinfo relies on an IANA database that may not be present. The tzdata package can be installed as a workaround. It's a first-party package, but is not in the standard library.

通知家属抬走 2024-07-12 22:40:40

我在 python-dateutil 方面取得了最大的成功:

from dateutil import tz

def datetime_to_utc(date):
    """Returns date in UTC w/o tzinfo"""
    return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date

I've had the most success with python-dateutil:

from dateutil import tz

def datetime_to_utc(date):
    """Returns date in UTC w/o tzinfo"""
    return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date
何止钟意 2024-07-12 22:40:40

还有一个使用 pytz 的示例,但包含 localize(),这拯救了我的一天。

import pytz, datetime
utc = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S'
amsterdam = pytz.timezone('Europe/Amsterdam')

dt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)
am_dt = amsterdam.localize(dt)
print am_dt.astimezone(utc).strftime(fmt)
'2012-04-06 08:00:00'

One more example with pytz, but includes localize(), which saved my day.

import pytz, datetime
utc = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S'
amsterdam = pytz.timezone('Europe/Amsterdam')

dt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)
am_dt = amsterdam.localize(dt)
print am_dt.astimezone(utc).strftime(fmt)
'2012-04-06 08:00:00'
风苍溪 2024-07-12 22:40:40
def local_to_utc(t):
    secs = time.mktime(t)
    return time.gmtime(secs)

def utc_to_local(t):
    secs = calendar.timegm(t)
    return time.localtime(secs)

来源:http://feihonghsu.blogspot。 com/2008/02/converting-from-local-time-to-utc.html

来自 bd808:如果您的源是 datetime.datetime 对象 t,则调用为:

local_to_utc(t.timetuple())
def local_to_utc(t):
    secs = time.mktime(t)
    return time.gmtime(secs)

def utc_to_local(t):
    secs = calendar.timegm(t)
    return time.localtime(secs)

Source: http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html

Example usage from bd808: If your source is a datetime.datetime object t, call as:

local_to_utc(t.timetuple())
梦里兽 2024-07-12 22:40:40

我对 dateutil 很幸运(对于其他相关问题,它被广泛推荐):(

from datetime import *
from dateutil import *
from dateutil.tz import *

# METHOD 1: Hardcode zones:
utc_zone = tz.gettz('UTC')
local_zone = tz.gettz('America/Chicago')
# METHOD 2: Auto-detect zones:
utc_zone = tz.tzutc()
local_zone = tz.tzlocal()

# Convert time string to datetime
local_time = datetime.strptime("2008-09-17 14:02:00", '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in local time zone since 
# datetime objects are 'naive' by default
local_time = local_time.replace(tzinfo=local_zone)
# Convert time to UTC
utc_time = local_time.astimezone(utc_zone)
# Generate UTC time string
utc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S')

代码源自此答案 Convert UTC datetime string to local datetime

I'm having good luck with dateutil (which is widely recommended on SO for other related questions):

from datetime import *
from dateutil import *
from dateutil.tz import *

# METHOD 1: Hardcode zones:
utc_zone = tz.gettz('UTC')
local_zone = tz.gettz('America/Chicago')
# METHOD 2: Auto-detect zones:
utc_zone = tz.tzutc()
local_zone = tz.tzlocal()

# Convert time string to datetime
local_time = datetime.strptime("2008-09-17 14:02:00", '%Y-%m-%d %H:%M:%S')

# Tell the datetime object that it's in local time zone since 
# datetime objects are 'naive' by default
local_time = local_time.replace(tzinfo=local_zone)
# Convert time to UTC
utc_time = local_time.astimezone(utc_zone)
# Generate UTC time string
utc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S')

(Code was derived from this answer to Convert UTC datetime string to local datetime)

陌伤ぢ 2024-07-12 22:40:40

以下是常见 Python 时间转换的摘要。

有些方法会丢失几分之一秒,并用 (s) 标记。 可以使用诸如ts = (d - epoch)/unit之类的显式公式来代替(感谢 jfs)。

  • struct_time (UTC) → POSIX (s):
    calendar.timegm(struct_time)
  • Naïve datetime (local) → POSIX (s) :
    calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
    (DST 转换期间的异常,请参阅 jfs 的评论)
  • Naïve datetime (UTC) → POSIX (s):
    calendar.timegm(dt.utctimetuple())
  • 感知日期时间 → POSIX (s):
    calendar.timegm(dt.utctimetuple())
  • POSIX → struct_time (UTC, s):
    time.gmtime(t)< br>(参见 jfs 的评论)
  • Naïve datetime(本地)→ struct_time(UTC,s):
    stz.localize(dt, is_dst=None).utctimetuple()
    (DST 转换期间的异常,请参阅 jfs 的评论)
  • Naïve datetime (UTC) → struct_time (UTC, s):
    dt.utctimetuple()
  • 感知日期时间 → struct_time (UTC, s):
    dt.utctimetuple()
  • POSIX → Naïve 日期时间 (本地):
    datetime.fromtimestamp (t,无)
    (在某些情况下可能会失败,请参阅下面 jfs 的评论)
  • struct_time (UTC) → Naïve datetime(本地,s):
    datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
    (无法表示闰秒,请参阅 jfs 的评论)
  • Naïve datetime ( UTC) → Naïve 日期时间(本地):
    dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
  • 感知日期时间 → Naïve 日期时间(本地):
    dt.astimezone(tz).replace(tzinfo=None)
  • POSIX → Naïve datetime (UTC):
    datetime.utcfromtimestamp(t)
  • struct_time (UTC) → Naïve datetime(UTC,s):
    datetime.datetime(*struct_time[:6])
    (不能表示闰秒,请参阅评论jfs)
  • 朴素日期时间(本地)→ 朴素日期时间 (UTC):
    stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
    ( DST 转换期间出现异常,请参阅 jfs 的评论)
  • 感知日期时间 → Naïve 日期时间 (UTC):
    dt.astimezone(UTC).replace(tzinfo=None)
  • POSIX → 感知日期时间:
    datetime.fromtimestamp(t, tz)
    (对于非 pytz 时区可能会失败)
  • struct_time (UTC) → 感知日期时间(s)
    datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
    (不能表示闰秒,请参阅 jfs 的评论)
  • Naïve datetime (local) → Aware datetime:< br>stz.localize(dt, is_dst=None)
    (DST 转换期间的异常,请参阅 jfs 的评论)
  • Naïve 日期时间 (UTC) → 感知日期时间:
    dt。替换(tzinfo=UTC)

来源:taaviburns.ca

Here's a summary of common Python time conversions.

Some methods drop fractions of seconds, and are marked with (s). An explicit formula such as ts = (d - epoch) / unit can be used instead (thanks jfs).

  • struct_time (UTC) → POSIX (s):
    calendar.timegm(struct_time)
  • Naïve datetime (local) → POSIX (s):
    calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
    (exception during DST transitions, see comment from jfs)
  • Naïve datetime (UTC) → POSIX (s):
    calendar.timegm(dt.utctimetuple())
  • Aware datetime → POSIX (s):
    calendar.timegm(dt.utctimetuple())
  • POSIX → struct_time (UTC, s):
    time.gmtime(t)
    (see comment from jfs)
  • Naïve datetime (local) → struct_time (UTC, s):
    stz.localize(dt, is_dst=None).utctimetuple()
    (exception during DST transitions, see comment from jfs)
  • Naïve datetime (UTC) → struct_time (UTC, s):
    dt.utctimetuple()
  • Aware datetime → struct_time (UTC, s):
    dt.utctimetuple()
  • POSIX → Naïve datetime (local):
    datetime.fromtimestamp(t, None)
    (may fail in certain conditions, see comment from jfs below)
  • struct_time (UTC) → Naïve datetime (local, s):
    datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
    (can't represent leap seconds, see comment from jfs)
  • Naïve datetime (UTC) → Naïve datetime (local):
    dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
  • Aware datetime → Naïve datetime (local):
    dt.astimezone(tz).replace(tzinfo=None)
  • POSIX → Naïve datetime (UTC):
    datetime.utcfromtimestamp(t)
  • struct_time (UTC) → Naïve datetime (UTC, s):
    datetime.datetime(*struct_time[:6])
    (can't represent leap seconds, see comment from jfs)
  • Naïve datetime (local) → Naïve datetime (UTC):
    stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
    (exception during DST transitions, see comment from jfs)
  • Aware datetime → Naïve datetime (UTC):
    dt.astimezone(UTC).replace(tzinfo=None)
  • POSIX → Aware datetime:
    datetime.fromtimestamp(t, tz)
    (may fail for non-pytz timezones)
  • struct_time (UTC) → Aware datetime (s):
    datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
    (can't represent leap seconds, see comment from jfs)
  • Naïve datetime (local) → Aware datetime:
    stz.localize(dt, is_dst=None)
    (exception during DST transitions, see comment from jfs)
  • Naïve datetime (UTC) → Aware datetime:
    dt.replace(tzinfo=UTC)

Source: taaviburns.ca

各自安好 2024-07-12 22:40:40

自 Python 3.6 起可用的选项:datetime.astimezone(tz=None) 可用于获取表示本地时间的感知日期时间对象(文档)。 然后可以轻松地将其转换为 UTC。

from datetime import datetime, timezone
s = "2008-09-17 14:02:00"

# to datetime object:
dt = datetime.fromisoformat(s) # Python 3.7

# I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008
dt = dt.astimezone()
print(dt)
# 2008-09-17 14:02:00+02:00

# ...and to UTC:
dtutc = dt.astimezone(timezone.utc)
print(dtutc)
# 2008-09-17 12:02:00+00:00
  • 注意:虽然所描述的到 UTC 的转换工作得很好,但是 .astimezone() 将 datetime 对象的 tzinfo 设置为 timedelta 派生的时区 - 所以不要期望任何“ DST 意识”来自它。 这里要小心 timedelta 算术。 当然,除非您先转换为 UTC。
  • 相关:获取 Windows 上的本地时区名称(Python 3.9 zoneinfo)

An option available since Python 3.6: datetime.astimezone(tz=None) can be used to get an aware datetime object representing local time (docs). This can then easily be converted to UTC.

from datetime import datetime, timezone
s = "2008-09-17 14:02:00"

# to datetime object:
dt = datetime.fromisoformat(s) # Python 3.7

# I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008
dt = dt.astimezone()
print(dt)
# 2008-09-17 14:02:00+02:00

# ...and to UTC:
dtutc = dt.astimezone(timezone.utc)
print(dtutc)
# 2008-09-17 12:02:00+00:00
  • Note: while the described conversion to UTC works perfectly fine, .astimezone() sets tzinfo of the datetime object to a timedelta-derived timezone - so don't expect any "DST-awareness" from it. Be careful with timedelta arithmetic here. Unless you convert to UTC first of course.
  • related: Get local time zone name on Windows (Python 3.9 zoneinfo)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文