import datetime
# 获取当前UTC时区的时间
def now():
return datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
# return datetime.datetime.now(datetime.datetime.timezone.utc)
# 时区转换函数
def astimezone(d :datetime.datetime, offset):
return d.astimezone(datetime.timezone(datetime.timedelta(hours=offset)))
# ISO 8601时间格式 [YYYY]-[MM]-[DD]T[hh]:[mm]:[ss]+-[TZ]
# 将字符串时间转换为datetime对象
def parse_iso8601(strdate :str):
date, time = strdate.split('T', 1)
if '-' in time:
time, tz = time.split('-')
tz = '-' + tz
elif '+' in time:
time, tz = time.split('+')
tz = '+' + tz
elif 'Z' in time:
time = time[:-1]
tz = '+0000'
date = date.replace('-', '')
time = time.replace(':', '')
tz = tz.replace(':', '')
return datetime.datetime.strptime('{}T{}{}'.format(date, time, tz), "%Y%m%dT%H%M%S%z")
# 转换为utc时间
def asutc(d :datetime.datetime):
return d.astimezone(datetime.timezone.utc)
# 转换时间戳为datetime
ts = 1521588268
d = datetime.datetime.utcfromtimestamp(ts)
d.timestamp() # d 简单型datetime代表本地时间
d.replace(tzinfo=datetime.timezone.utc).timestamp()
import locale
import contextlib
@contextlib.contextmanager
def switchlocale(name):
prev = locale.getlocale()
locale.setlocale(locale.LC_ALL, name)
yield
locale.setlocale(locale.LC_ALL, prev)
def format_date(loc, d):
with switchlocale(loc):
fmt = locale.nl_langinfo(locale.D_T_FMT)
return d.strftime(fmt)