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

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

我确定我之前已经做过,但是找不到它,因此SO希望将来可以帮助我(和其他人)做到这一点。

说明:例如,如果我2008-09-17 14:02:00在当地的时区(+10)中,我想生成一个具有相等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.


回答 0

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

使用pytz包含时区+ UTC完整列表的模块。弄清楚本地时区是什么,从中构造一个时区对象,然后将其操纵并附加到原始日期时间。

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

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

import pytz, datetime
local = pytz.timezone ("America/Los_Angeles")
naive = datetime.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 documentation for datetime.strptime for information on parsing the date string.

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”:

import pytz, datetime
local = pytz.timezone ("America/Los_Angeles")
naive = datetime.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")

回答 1

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-need-to-know-about-date-and-time-in-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
>>> dt_now = datetime.now(tz=timezone.utc)
>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)

for details see: 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 your 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


回答 2

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

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:

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


回答 3

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

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

  • struct_time(UTC)→POSIX (s)
    calendar.timegm(struct_time)
  • 原始日期时间(本地)→POSIX (秒):(
    calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
    DST转换期间的异常,请参阅jfs的注释)
  • 原始日期时间(UTC)→POSIX (s)
    calendar.timegm(dt.utctimetuple())
  • 知道日期时间→POSIX (S)
    calendar.timegm(dt.utctimetuple())
  • POSIX→struct_time(UTC,s):(
    time.gmtime(t)
    请参阅jfs的评论)
  • 原始日期时间(本地)→struct_time(UTC,s):(
    stz.localize(dt, is_dst=None).utctimetuple()
    DST转换期间的异常,请参阅jfs的注释)
  • 原始日期时间(UTC)→struct_time(UTC,s):
    dt.utctimetuple()
  • 知道日期时间→struct_time(UTC,s):
    dt.utctimetuple()
  • POSIX→原始日期时间(本地):(
    datetime.fromtimestamp(t, None)
    在某些情况下可能会失败,请参见下面来自jfs的评论)
  • struct_time(UTC)→原始日期时间(本地,s):
    datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
    不能表示leap秒,请参见jfs的注释)
  • 原始日期时间(UTC)→原始日期时间(本地):
    dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
  • 知道日期时间→天真日期时间(本地):
    dt.astimezone(tz).replace(tzinfo=None)
  • POSIX→原始日期时间(UTC):
    datetime.utcfromtimestamp(t)
  • struct_time(UTC)→原始日期时间(UTC,s):(
    datetime.datetime(*struct_time[:6])
    不能表示leap秒,请参阅jfs的注释)
  • 原始日期时间(本地)→原始日期时间(UTC):
    stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
    DST转换期间的异常,请参阅jfs的注释)
  • 知道日期时间→原始日期时间(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)
    不能表示leap秒,请参阅jfs的注释)
  • 原始日期时间(本地)→感知日期时间:
    stz.localize(dt, is_dst=None)
    (DST转换期间的异常,请参阅jfs的注释)
  • 原始日期时间(UTC)→知道日期时间:
    dt.replace(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


回答 4

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.datetimeobject 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())

回答 5

我对dateutil感到好运(广泛建议在SO上解决其他相关问题):

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')

(代码从此答案派生而来,将UTC datetime字符串转换为本地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)


回答 6

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'

回答 7

我在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

回答 8

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'

回答 9

如果您更喜欢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")

回答 10

简单

我这样做是这样的:

>>> 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

回答 11

您可以执行以下操作:

>>> 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

回答 12

怎么样 –

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.


回答 13

用于避开日光节约等。

上述答案都没有特别帮助我。以下代码适用于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>)

回答 14

使用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 :)


回答 15

我在这里找到了另一个问题的最佳答案。它仅使用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)

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

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.


回答 16

我的一个项目中有以下代码:

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")

回答 17

在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) 

回答 18

怎么样 –

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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。