datetime으로 파이썬에서 UTC 타임 스탬프 가져 오기
날짜를 지정하여 UTC 타임 스탬프를 얻는 방법이 있습니까? 내가 기대하는 것 :
datetime(2008, 1, 1, 0, 0, 0, 0)
결과해야
1199145600
순진한 datetime 객체를 만드는 것은 시간대 정보가 없음을 의미합니다. datetime.utcfromtimestamp에 대한 설명서를 보면 UTC 타임 스탬프를 만드는 것은 표준 시간대 정보를 제외하는 것을 의미합니다. 그래서 순진한 datetime 객체를 만들면 (내가했던 것처럼) UTC 타임 스탬프가 나올 것이라고 생각합니다. 하나:
then = datetime(2008, 1, 1, 0, 0, 0, 0)
datetime.utcfromtimestamp(float(then.strftime('%s')))
결과
2007-12-31 23:00:00
datetime 객체에 여전히 숨겨진 시간대 정보가 있습니까? 내가 도대체 뭘 잘못하고있는 겁니까?
순진한 datetime
대 인식datetime
기본 datetime
개체는 "순진한"이라고합니다. 표준 시간대 정보없이 시간 정보를 유지합니다. 순진한 출처가 분명하지 않은 datetime
상대 숫자 (예 :) 로 생각하십시오 +4
(실제로 출처는 시스템 경계 전체에서 공통적입니다).
대조적으로, 인식 은 전 세계에 공통된 기원을 가진 datetime
절대 숫자 (예 :) 로 생각 8
하십시오.
시간대 정보가 없으면 "순진한"날짜 시간을 순진하지 않은 시간 표현으로 변환 할 수 없습니다 ( +4
어디에서 시작해야할지 모르는 경우 대상은 어디에 있습니까?). 이것이 당신이 datetime.datetime.toutctimestamp()
방법을 가질 수없는 이유 입니다. (cf : http://bugs.python.org/issue1457227 )
당신이 있는지 확인하려면 datetime
dt
순진, 체크 인 dt.tzinfo
경우, None
그때는 순진입니다 :
datetime.now() ## DANGER: returns naïve datetime pointing on local time
datetime(1970, 1, 1) ## returns naïve datetime pointing on user given time
순진한 날짜 시간이 있습니다. 어떻게해야합니까?
특정 상황에 따라 가정해야합니다. 스스로에게 물어봐야 할 질문은 다음과 같습니다 datetime
. 아니면 현지 시간 이었습니까?
UTC를 사용하는 경우 (문제가 없음) :
import calendar def dt2ts(dt): """Converts a datetime object to UTC timestamp naive datetime will be considered UTC. """ return calendar.timegm(dt.utctimetuple())
UTC를 사용하지 않았다면 지옥에 오신 것을 환영합니다.
datetime
이전 기능을 사용하기 전에 의도 한 시간대를 되돌려 비 순진 하게 만들어야합니다 .당신이 필요합니다 시간대의 이름 과 DST가 유효했던 경우에 대한 정보 대상 순진의 날짜를 (DST에 대한 마지막 정보가 cornercases 필요) 생산시를 :
import pytz ## pip install pytz mytz = pytz.timezone('Europe/Amsterdam') ## Set your timezone dt = mytz.normalize(mytz.localize(dt, is_dst=True)) ## Set is_dst accordingly
제공하지 않은 결과
is_dst
:사용하지
is_dst
않으면 역방향 DST가 적용되는 동안 대상 날짜 시간이 생성 된 경우 (예 : 1 시간을 제거하여 DST 시간 변경) 잘못된 시간 (및 UTC 타임 스탬프)이 생성됩니다.is_dst
물론 잘못된 것을 제공 하면 DST 겹침이나 구멍에서만 잘못된 시간 (및 UTC 타임 스탬프)이 생성됩니다. 그리고 "구멍"(전진 DST로 인해 존재하지 않았던 시간)에서 발생하는 잘못된 시간도is_dst
제공하면이 가짜 시간을 고려하는 방법에 대한 해석을 제공 할 수 있으며, 이것이.normalize(..)
실제로 여기서 뭔가를 수행 할 유일한 경우입니다. 그런 다음 실제 유효한 시간으로 변환합니다 (필요한 경우 날짜 시간 및 DST 개체 변경). 주.normalize()
당신이 특히 다른 곳에서이 변수를 다시 사용, 마지막에 정확한 UTC 타임 스탬프를 가지고 필요하지 않습니다,하지만 당신은 당신의 변수에 가짜 시간을 갖는 아이디어를 싫어하는 경우 아마 좋습니다.그리고 다음을 사용하지 마십시오 : (cf : pytz를 사용한 Datetime 시간대 변환 )
dt = dt.replace(tzinfo=timezone('Europe/Amsterdam')) ## BAD !!
왜? 때문에
.replace()
맹목적으로 대체합니다tzinfo
계정에 목표 시간을내어과 나쁜 DST 객체를 선택합니다없이. 반면.localize()
목표 시간과is_dst
힌트를 사용하여 올바른 DST 개체를 선택합니다.
오래된 오답 (이 문제를 제기 한 @JFSebastien에게 감사드립니다) :
바라건대, datetime
순진한 datetime 객체 생성과 원하는 순간 사이에 변경하지 않을 시스템 구성과 관련이 있기 때문에 순진한 객체 를 만들 때 시간대 (로컬 원본)를 추측하기가 매우 쉽습니다 . UTC 타임 스탬프. 이 트릭은 불완전한 질문을 하는 데 사용될 수 있습니다 .
사용하여 time.mktime
다음을 만들 수 있습니다 utc_mktime
.
def utc_mktime(utc_tuple):
"""Returns number of seconds elapsed since epoch
Note that no timezone are taken into consideration.
utc tuple must be: (year, month, day, hour, minute, second)
"""
if len(utc_tuple) == 6:
utc_tuple += (0, 0, 0)
return time.mktime(utc_tuple) - time.mktime((1970, 1, 1, 0, 0, 0, 0, 0, 0))
def datetime_to_timestamp(dt):
"""Converts a datetime object to UTC timestamp"""
return int(utc_mktime(dt.timetuple()))
datetime
.NET Framework를 생성 한 시간대와 동일한 시간대에 개체가 생성 되었는지 확인해야 합니다 datetime
.
이 마지막 솔루션은 지금부터 UTC 오프셋이 EPOCH의 UTC 오프셋과 동일하다고 가정하기 때문에 올바르지 않습니다. 많은 시간대 (일광 절약 시간 (DST) 오프셋에 대한 연중 특정 순간)에는 해당되지 않습니다.
또 다른 가능성은 다음과 같습니다.
d = datetime.datetime.utcnow()
epoch = datetime.datetime(1970,1,1)
t = (d - epoch).total_seconds()
"d"와 "epoch"는 모두 순진한 날짜 시간이므로 "-"연산자를 유효하게 만들고 간격을 반환합니다. total_seconds()
간격을 초로 바꿉니다. total_seconds()
플로트 를 반환합니다.d.microsecond == 0
Also note the calendar.timegm() function as described by this blog entry:
import calendar
calendar.timegm(utc_timetuple)
The output should agree with the solution of vaab.
If input datetime object is in UTC:
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> timestamp = (dt - datetime(1970, 1, 1)).total_seconds()
1199145600.0
Note: it returns float i.e., microseconds are represented as fractions of a second.
If input date object is in UTC:
>>> from datetime import date
>>> utc_date = date(2008, 1, 1)
>>> timestamp = (utc_date.toordinal() - date(1970, 1, 1).toordinal()) * 24*60*60
1199145600
See more details at Converting datetime.date to UTC timestamp in Python.
I feel like the main answer is still not so clear, and it's worth taking the time to understand time and timezones.
The most important thing to understand when dealing with time is that time is relative!
2017-08-30 13:23:00
: (a naive datetime), represents a local time somewhere in the world, but note that2017-08-30 13:23:00
in London is NOT THE SAME TIME as2017-08-30 13:23:00
in San Francisco.
Because the same time string can be interpreted as different points-in-time depending on where you are in the world, there is a need for an absolute notion of time.
A UTC timestamp is a number in seconds (or milliseconds) from Epoch (defined as 1 January 1970 00:00:00
at GMT
timezone +00:00 offset).
Epoch is anchored on the GMT timezone and therefore is an absolute point in time. A UTC timestamp being an offset from an absolute time therefore defines an absolute point in time.
This makes it possible to order events in time.
Without timezone information, time is relative, and cannot be converted to an absolute notion of time without providing some indication of what timezone the naive datetime should be anchored to.
What are the types of time used in computer system?
naive datetime: usually for display, in local time (i.e. in the browser) where the OS can provide timezone information to the program.
UTC timestamps: A UTC timestamp is an absolute point in time, as mentioned above, but it is anchored in a given timezone, so a UTC timestamp can be converted to a datetime in any timezone, however it does not contain timezone information. What does that mean? That means that 1504119325 corresponds to
2017-08-30T18:55:24Z
, or2017-08-30T17:55:24-0100
or also2017-08-30T10:55:24-0800
. It doesn't tell you where the datetime recorded is from. It's usually used on the server side to record events (logs, etc...) or used to convert a timezone aware datetime to an absolute point in time and compute time differences.ISO-8601 datetime string: The ISO-8601 is a standardized format to record datetime with timezone. (It's in fact several formats, read on here: https://en.wikipedia.org/wiki/ISO_8601) It is used to communicate timezone aware datetime information in a serializable manner between systems.
When to use which? or rather when do you need to care about timezones?
If you need in any way to care about time-of-day, you need timezone information. A calendar or alarm needs time-of-day to set a meeting at the correct time of the day for any user in the world. If this data is saved on a server, the server needs to know what timezone the datetime corresponds to.
To compute time differences between events coming from different places in the world, UTC timestamp is enough, but you lose the ability to analyze at what time of day events occured (ie. for web analytics, you may want to know when users come to your site in their local time: do you see more users in the morning or the evening? You can't figure that out without time of day information.
Timezone offset in a date string:
Another point that is important, is that timezone offset in a date string is not fixed. That means that because 2017-08-30T10:55:24-0800
says the offset -0800
or 8 hours back, doesn't mean that it will always be!
In the summer it may well be in daylight saving time, and it would be -0700
What that means is that timezone offset (+0100) is not the same as timezone name (Europe/France) or even timezone designation (CET)
America/Los_Angeles
timezone is a place in the world, but it turns into PST
(Pacific Standard Time) timezone offset notation in the winter, and PDT
(Pacific Daylight Time) in the summer.
So, on top of getting the timezone offset from the datestring, you should also get the timezone name to be accurate.
Most packages will be able to convert numeric offsets from daylight saving time to standard time on their own, but that is not necessarily trivial with just offset. For example WAT
timezone designation in West Africa, is UTC+0100 just like CET
timezone in France, but France observes daylight saving time, while West Africa does not (because they're close to the equator)
So, in short, it's complicated. VERY complicated, and that's why you should not do this yourself, but trust a package that does it for you, and KEEP IT UP TO DATE!
There is indeed a problem with using utcfromtimestamp and specifying time zones. A nice example/explanation is available on the following question:
How to specify time zone (UTC) when converting to Unix time? (Python)
The accepted answer seems not work for me. My solution:
import time
utc_0 = int(time.mktime(datetime(1970, 01, 01).timetuple()))
def datetime2ts(dt):
"""Converts a datetime object to UTC timestamp"""
return int(time.mktime(dt.utctimetuple())) - utc_0
Simplest way:
>>> from datetime import datetime
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> dt.strftime("%s")
'1199163600'
Edit: @Daniel is correct, this would convert it to the machine's timezone. Here is a revised answer:
>>> from datetime import datetime, timezone
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> int((dt-epoch).total_seconds())
'1199145600'
In fact, its not even necessary to specify timezone.utc
, because the time difference is the same so long as both datetime
have the same timezone (or no timezone).
>>> from datetime import datetime
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> int((dt-epoch).total_seconds())
1199145600
참고URL : https://stackoverflow.com/questions/5067218/get-utc-timestamp-in-python-with-datetime
'Nice programing' 카테고리의 다른 글
만드는 방법 (0) | 2020.10.26 |
---|---|
빌드 전용 장치는이 대상을 실행하는 데 사용할 수 없습니다. (0) | 2020.10.26 |
일치하는 줄 이후부터 파일의 모든 줄을 삭제하려면 어떻게해야합니까? (0) | 2020.10.26 |
Objective-C : 초기화 대 초기화 (0) | 2020.10.26 |
파이썬 히스토그램에 로그 빈을 갖는 방법 (0) | 2020.10.26 |