Nasıl bir yerel datetime sadece python standart Kütüphanesi kullanılarak python utc datetime dönüştürmek için?
Datetime kullanarak oluşturulan python datetime bir örneği var.() utcnow ve veritabanında korunur.
Görüntülemek için, yerel datetime Varsayılan yerel zaman dilimini kullanarak datetime örneği veritabanından yeniden dönüştürmek istiyorum (örneğin datetime gibi datetime kullanarak oluşturun.(şimdi)
Nasıl bir yerel datetime sadece python standart kütüphane (pytz bağımlılık gibi) kullanarak utc datetime dönüştürebilirsiniz?
Bir çözüm datetime kullanmak olacaktır gibi görünüyor.astimezone( tz ), ama nasıl varsayılan olsun mu istiyorsunuz yerel saat dilimi?
CEVAP
Python 3.3 :
from datetime import timezone
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)
2/3: Python
import calendar
from datetime import datetime, timedelta
def utc_to_local(utc_dt):
# get integer timestamp to avoid precision lost
timestamp = calendar.timegm(utc_dt.timetuple())
local_dt = datetime.fromtimestamp(timestamp)
assert utc_dt.resolution >= timedelta(microseconds=1)
return local_dt.replace(microsecond=utc_dt.microsecond)
pytz (Python 2/3) kullanarak:
import pytz
local_tz = pytz.timezone('Europe/Moscow') # use your local timezone name here
# NOTE: pytz.reference.LocalTimezone() would produce wrong result here
## You could use `tzlocal` module to get local timezone on Unix and Win32
# from tzlocal import get_localzone # $ pip install tzlocal
# # get local timezone
# local_tz = get_localzone()
def utc_to_local(utc_dt):
local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
return local_tz.normalize(local_dt) # .normalize might be unnecessary
Örnek
def aslocaltimestr(utc_dt):
return utc_to_local(utc_dt).strftime('%Y-%m-%d %H:%M:%S.%f %Z%z')
print(aslocaltimestr(datetime(2010, 6, 6, 17, 29, 7, 730000)))
print(aslocaltimestr(datetime(2010, 12, 6, 17, 29, 7, 730000)))
print(aslocaltimestr(datetime.utcnow()))
Çıktı
Python 3.32010-06-06 21:29:07.730000 MSD 0400
2010-12-06 20:29:07.730000 MSK 0300
2012-11-08 14:19:50.093745 MSK 0400
Python 2
2010-06-06 21:29:07.730000
2010-12-06 20:29:07.730000
2012-11-08 14:19:50.093911
pytz
2010-06-06 21:29:07.730000 MSD 0400
2010-12-06 20:29:07.730000 MSK 0300
2012-11-08 14:19:50.146917 MSK 0400
Not: hesap DST utc ve son değişiklik MSK bunun için ofset içine alır.
Olmayan pytz çözümleri Windows üzerinde çalışma olup olmadığını bilmiyorum.

Nasıl bir python dönüştürmek.bir datet...
Ne N saniye datetime eklemek için stan...
Nasıl üstesinden gelmek için "dat...
Nasıl Python epoch (unix zaman) beri m...
Nasıl yerel saat UTC dönüştürmek için ...