[英]How to convert local time string to UTC?
如何將本地時間的日期時間字符串轉換為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 時間。
首先,將字符串解析為一個簡單的日期時間 object。 這是一個沒有附加時區信息的datetime.datetime
實例。 請參閱其文檔。
使用pytz
模塊,它帶有完整的時區列表 + UTC。 弄清楚本地時區是什么,從中構造一個時區 object,然后對其進行操作並將其附加到天真的日期時間。
最后,使用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")
注意- 自 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
datetime 模塊的utcnow() function 可用於獲取當前 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
可用。 您可以使用以下命令生成時區感知日期時間 object:
import datetime
timezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)
如果您准備好進行時區轉換 go 閱讀以下內容:
感謝@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
自紀元以來的秒數->本地時區中的元組
下面總結一下常見的Python時間換算。
有些方法會減少幾分之一秒,並用(s)標記。 可以改用諸如ts = (d - epoch) / unit
之類的顯式公式(感謝 jfs)。
calendar.timegm(struct_time)
calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())
calendar.timegm(dt.utctimetuple())
calendar.timegm(dt.utctimetuple())
time.gmtime(t)
stz.localize(dt, is_dst=None).utctimetuple()
dt.utctimetuple()
dt.utctimetuple()
datetime.fromtimestamp(t, None)
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)
dt.astimezone(tz).replace(tzinfo=None)
datetime.utcfromtimestamp(t)
datetime.datetime(*struct_time[:6])
stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)
dt.astimezone(UTC).replace(tzinfo=None)
datetime.fromtimestamp(t, tz)
datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)
stz.localize(dt, is_dst=None)
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
object t
,請調用:
local_to_utc(t.timetuple())
我對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 日期時間字符串轉換為本地日期時間的答案)
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'
自 Python 3.6 起可用的選項: datetime.astimezone(tz=None)
可用於獲取表示本地時間(docs)的感知日期時間 object 。 然后可以輕松地將其轉換為 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()
將日期時間 object 的tzinfo
設置為 timedelta 派生的時區 - 所以不要期望它有任何“DST 意識”。
我在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
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.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")
我是這樣做的:
>>> 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
你可以這樣做:
>>> 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))
如果 seconds 為None
則它將本地時間轉換為 UTC 時間,否則將傳入的時間轉換為 UTC。
這是Python3.9 中原生zoneinfo模塊的示例:
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 package 作為解決方法。 它是第一方 package,但不在標准庫中。
使用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')
這個圖書館讓生活變得輕松:)
我的一個項目中有這段代碼:
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")
在 python 3.9.0 中,將本地時間local_time
解析為datetime.datetime
object 后,只需使用local_time.astimezone(datetime.timezone.utc)
。
用於避開夏令時等。
以上答案都沒有對我特別有幫助。 下面的代碼適用於 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>)
我在這里找到了另一個問題的最佳答案。 它僅使用 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)
我在這里重新發布答案,因為這個問題會根據搜索關鍵字在谷歌中彈出,而不是鏈接問題。
如果您已經有日期時間 object my_dt
您可以將其更改為 UTC:
datetime.datetime.utcfromtimestamp(my_dt.timestamp())
對於任何對最受好評的答案感到困惑的人。 您可以通過生成日期時間 object 將日期時間字符串轉換為 python 中的 utc 時間,然后您可以使用 astimezone(pytz.utc) 以 utc 獲取日期時間。
例如。
假設我們有本地日期時間字符串為2021-09-02T19:02:00Z
的 isoformat
現在將此字符串轉換為 utc 日期時間。 我們首先需要使用這個字符串生成日期時間 object
dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')
這將為您提供 python 日期時間 object,然后您可以使用astimezone(pytz.utc)
來獲取 utc 日期時間
dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ') dt = dt.astimezone(pytz.utc)
這將為您提供 UTC 格式的日期時間 object,然后您可以使用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")
簡而言之,要將任何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")
然后,我們可以調用 function:
>>> to_utc(date)
datetime.datetime(2011, 2, 12, 1, 33, 54)
function 的工作原理:
>>> 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)
在python3中:
pip install python-dateutil
from dateutil.parser import tz
mydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None)
怎么樣 -
time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))
如果 seconds 為None
則它將本地時間轉換為 UTC 時間,否則將傳入的時間轉換為 UTC。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.