본문 바로가기

Python

[Python] Python Timezone conversion (feat. pytz replace & timezone)

반응형

 

pytz

https://stackoverflow.com/questions/10997577/python-timezone-conversion/18646797#18646797

 

Python Timezone conversion

How do I convert a time to another timezone in Python?

stackoverflow.com

 

from datetime import datetime
import pytz

utcmoment_naive = datetime.utcnow()
utcmoment = utcmoment_naive.replace(tzinfo=pytz.utc)

# print "utcmoment_naive: {0}".format(utcmoment_naive) # python 2
print("utcmoment_naive: {0}".format(utcmoment_naive))
print("utcmoment:       {0}".format(utcmoment))

localFormat = "%Y-%m-%d %H:%M:%S"

timezones = ['America/Los_Angeles', 'Europe/Madrid', 'America/Puerto_Rico']

for tz in timezones:
    localDatetime = utcmoment.astimezone(pytz.timezone(tz))
    print(localDatetime.strftime(localFormat))

# utcmoment_naive: 2017-05-11 17:43:30.802644
# utcmoment:       2017-05-11 17:43:30.802644+00:00
# 2017-05-11 10:43:30
# 2017-05-11 19:43:30
# 2017-05-11 13:43:30

So, with the moment of interest in the local timezone (a time that exists), you convert it to utc like this (reference).

localmoment_naive = datetime.strptime('2013-09-06 14:05:10', localFormat)

localtimezone = pytz.timezone('Australia/Adelaide')

try:
    localmoment = localtimezone.localize(localmoment_naive, is_dst=None)
    print("Time exists")

    utcmoment = localmoment.astimezone(pytz.utc)

except pytz.exceptions.NonExistentTimeError as e:
    print("NonExistentTimeError")

 

테스트

import datetime
import pytz
def test():
  timedelta = datetime.timedelta(hours=9)
  print("timedelta", timedelta)
  now = datetime.datetime.now()
  print("now", now)
  utcnow = datetime.datetime.utcnow()
  print("utcnow", utcnow)
  
  print("now", now + timedelta)
  print("utcnow", utcnow + timedelta)
  
  timezone = pytz.timezone("Asia/Seoul")
  utcnowtz = utcnow.replace(tzinfo=pytz.utc)
  seoul = utcnow.replace(tzinfo=timezone)
  print("utcnowtz", utcnowtz)
  print("replacetz", utcnow.replace(tzinfo=timezone))
  print("replacetz", utcnowtz.replace(tzinfo=timezone))
  print(">> seoultz", utcnowtz.astimezone(timezone))
  print("seoul", seoul)
  # print("Europe/Madrid", seoul.astimezone)


  
  return None
  
test()
결과

timedelta 9:00:00
now 2023-01-02 16:26:11.797305
utcnow 2023-01-02 07:26:11.797305
now 2023-01-03 01:26:11.797305
utcnow 2023-01-02 16:26:11.797305
utcnowtz 2023-01-02 07:26:11.797305+00:00
replacetz 2023-01-02 07:26:11.797305+08:28
replacetz 2023-01-02 07:26:11.797305+08:28
>> seoultz 2023-01-02 16:26:11.797305+09:00
seoul 2023-01-02 07:26:11.797305+08:28

 

pytz의 timezone을 사용하면 안되는 이유 (feat. replace)

replace로 timezone을 바꾸고 싶어서 쓰는데 timezone이 이상하게 나와서 안된다.

datetime.now(tz=timezone)으로 쓸때는 괜찮게 나오는데

다른곳에 쓸때는 거지같다;

 

https://stackoverflow.com/questions/1379740/pytz-localize-vs-datetime-replace

 

pytz localize vs datetime replace

I'm having some weird issues with pytz's .localize() function. Sometimes it wouldn't make adjustments to the localized datetime: .localize behaviour: >>> tz <DstTzInfo 'Africa/Abidjan...

stackoverflow.com

  timezone = pytz.timezone("Europe/Madrid")
  seoul = pytz.timezone("Asia/Seoul")
  target_date = now()
 
  print(datetime.now(tz=seoul))
  print(datetime.now(tz=timezone))
  print(datetime.now().replace(timezone=timezone))
  print(datetime.now(tz=seoul).astimezone(timezone))
  print(datetime(target_date.year, target_date.month, target_date.day, 0,0,0))
  print(datetime(target_date.year, target_date.month, target_date.day, 0,0,0, tzinfo=timezone))
결과값
2023-01-05 18:23:14.636876+09:00 (정상)
2023-01-05 10:23:14.636900+01:00 (정상)
2023-01-05 18:23:14.636919-00:15 (비정상)
2023-01-05 10:23:14.636937+01:00 (정상)
2022-12-10 00:00:00 (정상)
2022-12-10 00:00:00-00:15 (비정상)

TIMEZONE 바꾸는 방법

다른곳에서 못 찾아서 야매로 하는 방법

target_date = now()
timezone = pytz.timezone("Asia/Seoul")
timezone_date = datetime.now(tz=timezone).replace(year=target_date.year, month=target_date.month, day=target_date.day, hour=target_date.hour, minute=target_date.minute, second=target_date.second, microsecond=target_date.microsecond)
반응형