datetime 객체에서 pytz 시간대를 제거하려면 어떻게해야합니까?


121

pytz datetime 객체에서 시간대를 제거하는 간단한 방법이 있습니까?
예를 들면 재구성 dt에서 dt_tz이 예제 :

>>> import datetime
>>> import pytz
>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2012, 6, 8, 9, 27, 32, 601000)
>>> dt_tz = pytz.utc.localize(dt)
>>> dt_tz
datetime.datetime(2012, 6, 8, 9, 27, 32, 601000, tzinfo=<UTC>)

답변:


208

datetime 객체에서 시간대 (tzinfo)를 제거하려면 :

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

arrow 와 같은 라이브러리를 사용하는 경우 화살표 개체를 datetime 개체로 변환 한 다음 위의 예제와 동일한 작업을 수행하여 시간대를 제거 할 수 있습니다.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

왜 이렇게 하시겠습니까? 한 가지 예는 mysql이 DATETIME 유형의 시간대를 지원하지 않는다는 것입니다. 따라서 sqlalchemy와 같은 ORM을 사용 datetime.datetime하면 데이터베이스에 삽입 할 개체를 제공 할 때 단순히 시간대가 제거 됩니다. 해결책은 datetime.datetime객체를 UTC 로 변환 한 다음 (시간대를 지정할 수 없기 때문에 데이터베이스의 모든 것이 UTC가 됨) 데이터베이스에 삽입하거나 (어쨌든 시간대가 제거 된 위치) 직접 제거하는 것입니다. 또한 하나는 시간대를 인식하고 다른 하나는 시간대가 순진한 객체를 비교할 수 없습니다datetime.datetime .

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.