我怎样转换的日期时间 串在当地时间 来一个 串世界标准时间?

我敢肯定,我这样做之前,但不能找到它并因此希望将帮助我(和其他),在未来。

澄清:例如,如果我有 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时间。

有帮助吗?

解决方案 3

谢谢@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
串-->元组(没有时区的应用,使相匹配string)

time.mktime
当地时间tuple-->秒由于时元(总是当地时间)

time.gmtime
秒因为时代-->元组在UTC

calendar.timegm
tuple UTC-->秒因为时代

time.localtime
秒因为时代-->元组在当地的时区

其他提示

第一,分析的串成一个天真的datetime对象。这是一个实例 datetime.datetime 没有附加时区的信息。看看文件 datetime.strptime 对信息在分析日期串。

使用 pytz 模块,该模块涉及一个完整的列表中的次区域+UTC。找出当地的时区是,构建一个时区的目的,操纵,并附上它的幼稚的日期时间。

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

源代码,使用当地的时区的"美国/洛杉矶",为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)

从那里,你可以使用 strftime() 方法的格式UTC datetime为需要:

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

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.

如果你需要记录在那里的时候是采取、储存,分开。 不不 储存地时间+时区的信息!

注意到 -如果你的任何数据在一个区域使用的夏令时,使用 pytz 看看约翰*米利金的答复。

如果你想获得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'

-->或者,从一个已知的抵消,使用日期时间。话():

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

更新:

由于python3.2 datetime.timezone 是可用的。你可以产生一个时区,意识到datetime对象的命令如下:

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

这里有一个摘要的公共Python时间转换。

一些方法降级分秒钟,并标有 (s).明确的公式如 ts = (d - epoch) / unit 可以用来替代(谢谢jfs).

  • struct_time(UTC)→POSIX (s):
    calendar.timegm(struct_time)
  • 天真datetime(当地)→POSIX (s):
    calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
    (异常在DST过渡,见的评论jfs)
  • 天真datetime(UTC)→POSIX (s):
    calendar.timegm(dt.utctimetuple())
  • 意识到datetime→POSIX (s):
    calendar.timegm(dt.utctimetuple())
  • POSIX→struct_time(UTC, s):
    time.gmtime(t)
    (见的评论jfs)
  • 天真datetime(当地)→struct_time(UTC, s):
    stz.localize(dt, is_dst=None).utctimetuple()
    (异常在DST过渡,见的评论jfs)
  • 天真datetime(UTC)→struct_time(UTC, s):
    dt.utctimetuple()
  • 意识到datetime→struct_time(UTC, s):
    dt.utctimetuple()
  • POSIX→天真datetime(当地):
    datetime.fromtimestamp(t, None)
    (可能无法在某些条件,见的评论jfs下面)
  • struct_time(UTC)→天真datetime(地方、 s):
    datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
    (不能代表闰秒,看到的评论jfs)
  • 天真datetime(UTC)→天真datetime(当地):
    dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
  • 意识到datetime→天真datetime(当地):
    dt.astimezone(tz).replace(tzinfo=None)
  • POSIX→天真datetime(UTC):
    datetime.utcfromtimestamp(t)
  • struct_time(UTC)→天真datetime(UTC, s):
    datetime.datetime(*struct_time[:6])
    (不能代表闰秒,看到的评论jfs)
  • 天真datetime(当地)→天真datetime(UTC):
    stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
    (异常在DST过渡,见的评论jfs)
  • 意识到datetime→天真datetime(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)
  • 天真datetime(当地)→知的日期时间:
    stz.localize(dt, is_dst=None)
    (异常在DST过渡,见的评论jfs)
  • 天真datetime(UTC)→知的日期时间:
    dt.replace(tzinfo=UTC)

资料来源: taaviburns.ca

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

我有好运气 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')

(码是来自这个答案 转换UTC datetime串当地datetime)

一个例子与pytz,但是包括本地化(),其中救了我的一天。

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'

我有过的最成功 蟒蛇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
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'

如果你喜欢的日期时间。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")

你可以做到这一点:

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

怎么样-

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

如果秒 None 然后将它转换成本地时间为UTC时还将通过在时间UTC。

简单的

我没有这样的:

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

得到周围的一天-光节,等等。

没有一个以上答复特别帮助了我。代码下面的工作对于格林尼治标准时间。

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

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

这个图书馆让生活变得简单:)

在python3:

pip install python-dateutil

from dateutil.parser import tz

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

我找到最好的回答另一个问题 在这里,.它只使用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)

我重新张贴的答案在这里,因为这个问题出现在谷歌而不是联的问题取决于关键词搜索。

在这种情况下...pytz是最好的lib

import pytz
utc = pytz.utc
yourdate = datetime.datetime.now()
yourdateutc = yourdate.astimezone(utc).replace(tzinfo=None)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top