from datetime import timezone
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)
在Python 2/3中:
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):
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
def change_time_zone(year, month, day, hour):
hour = hour + 7 #<-- difference
if hour >= 24:
difference = hour - 24
hour = difference
day += 1
long_months = [1, 3, 5, 7, 8, 10, 12]
short_months = [4, 6, 9, 11]
if month in short_months:
if day >= 30:
day = 1
month += 1
if month > 12:
year += 1
elif month in long_months:
if day >= 31:
day = 1
month += 1
if month > 12:
year += 1
elif month == 2:
leap_years = [2000, 2004, 2008, 2012, 2016, 2020, 2024, 2028, 2032, 2036, 2040, 2044, 2048]
if year in leap_years:
if day >= 29:
day = 1
month += 1
if month > 12:
year += 1
elif year not in leap_years:
if day >= 28:
day = 1
month += 1
if month > 12:
year += 1
return datetime(int(year), int(month), int(day), int(hour), 00)
9 回答
在Python 3.3中:
在Python 2/3中:
使用
pytz
(Python 2/3):示例
输出
Python 3.3
Python 2
pytz
注意:它考虑了DST和MSK时区的最近utc偏移变化 .
我不知道非pytz解决方案是否适用于Windows .
你可以't do it with only the standard library as the standard library doesn't有任何时区 . 你需要pytz或dateutil .
或者,你可以通过实现自己的时区来实现没有pytz或dateutil . 但这很愚蠢 .
我想我想出来了:计算自纪元以来的秒数,然后使用time.localtime转换为本地timzeone,然后将时间结构转换回日期时间......
它适用于夏季/冬季DST:
标准Python库根本没有任何
tzinfo
实现 . 我一直认为这是日期时间模块的一个令人惊讶的缺点 .documentation for the tzinfo class确实附带了一些有用的例子 . 在该部分的末尾查找大代码块 .
你不能用标准库来做 . 使用 pytz 模块,您可以将任何天真/感知日期时间对象转换为任何其他时区 . 让我们看一些使用Python 3的例子 .
要将 naive 对象转换为任何其他时区,首先必须将其转换为 aware datetime对象 . 您可以使用
replace
方法将 naive datetime对象转换为 aware datetime对象 . 然后,要将 aware datetime对象转换为任何其他时区,您可以使用astimezone
方法 .变量
pytz.all_timezones
为您提供pytz模块中所有可用时区的列表 .因为
now
方法返回当前日期和时间,所以您必须首先了解datetime对象时区 .localize
函数将 naive datetime对象转换为时区感知日期时间对象 . 然后,您可以使用astimezone
方法将其转换为另一个时区 .以阿列克谢的评论为基础 . 这也适用于夏令时 .
一种简单(但可能有缺陷)的方法适用于Python 2和3:
它的优点是编写反函数是微不足道的
我找到的最简单的方法是获取你所在位置的时间偏移量,然后从小时中减去它 .
这适用于我,在Python 3.5.2中 .
这是另一种改变日期时间格式时区的方法(我知道我浪费了我的精力,但我没有看到这个页面,所以我不知道如何)没有分钟 . 和秒因为我的项目不需要它: