UNIX 시간으로 변환 할 때 시간대 (UTC)를 지정하는 방법은 무엇입니까? (파이썬)

StackOverflow https://stackoverflow.com/questions/1077285

문제

IS8601 형식의 UTC 타임 스탬프가 있으며 UNIX 시간으로 변환하려고합니다. 이것은 내 콘솔 세션입니다.

In [9]: mydate
Out[9]: '2009-07-17T01:21:00.000Z'
In [10]: parseddate = iso8601.parse_date(mydate)

In [14]: ti = time.mktime(parseddate.timetuple())

In [25]: datetime.datetime.utcfromtimestamp(ti)
Out[25]: datetime.datetime(2009, 7, 17, 7, 21)
In [26]: datetime.datetime.fromtimestamp(ti)
Out[26]: datetime.datetime(2009, 7, 17, 2, 21)

In [27]: ti
Out[27]: 1247815260.0
In [28]: parseddate
Out[28]: datetime.datetime(2009, 7, 17, 1, 21, tzinfo=<iso8601.iso8601.Utc object at 0x01D74C70>)

보시다시피, 나는 올바른 시간을 얻을 수 없습니다. TimeStamp ()에서 사용하면 시간이 1 씩 앞서고 utcfromtimestamp ()를 사용하면 6 시간이 지남에 따라갑니다.

어떤 충고?

감사!

도움이 되었습니까?

해결책

당신은 당신을 만들 수 있습니다 struct_time UTC에서 datetime.utctimetuple() 그런 다음 이것을 Unix 타임 스탬프로 변환하십시오 calendar.timegm():

calendar.timegm(parseddate.utctimetuple())

이것은 또한 일광 절약 시간 오프셋을 처리합니다. utctimetuple() 이것을 정상화합니다.

다른 팁

나는 단지 추측하고 있지만, 시간 구역 때문이 아니라 일광 절약/끄기 때문일 수 있습니다.

naive_utc_dt = parseddate.replace(tzinfo=None)
timestamp = (naive_utc_dt - datetime(1970, 1, 1)).total_seconds()
# -> 1247793660.0

자세한 내용을 참조하십시오 비슷한 질문에 대한 또 다른 대답.

그리고 뒤 :

utc_dt = datetime.utcfromtimestamp(timestamp)
# -> datetime.datetime(2009, 7, 17, 1, 21)
import time
import datetime
import calendar

def date_time_to_utc_epoch(dt_utc):         #convert from utc date time object (yyyy-mm-dd hh:mm:ss) to UTC epoch
    frmt="%Y-%m-%d %H:%M:%S"
    dtst=dt_utc.strftime(frmt)              #convert datetime object to string
    time_struct = time.strptime(dtst, frmt) #convert time (yyyy-mm-dd hh:mm:ss) to time tuple
    epoch_utc=calendar.timegm(time_struct)  #convert time to to epoch
    return epoch_utc

#----test function --------
now_datetime_utc = int(date_time_to_utc_epoch(datetime.datetime.utcnow()))
now_time_utc = int(time.time())

print (now_datetime_utc)
print (now_time_utc)

if now_datetime_utc == now_time_utc : 
    print ("Passed")  
else : 
    print("Failed")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top