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)
format_date('de_DE', datetime.datetime.utcnow())
format_date('en_GB', datetime.datetime.utcnow())
# 日期偏移, 每天0点0分0秒
def shiftdate(d, days):
return (
d.replace(hour=0, minute=0, second=0, microsecond=0) +
datetime.timedelta(days=days)
)
now = datetime.datetime.utcnow()
# tomorrow
shiftdate(now, 1)
# yesterday
shiftdate(now, -1)
# 月份偏移
def shiftmonth(d :datetime.datetime, months):
for _ in range(abs(months)):
if months > 0:
d = d.replace(day=5) + datetime.timedelta(days=28)
else:
d = d.replace(day=1) - datetime.timedelta(days=1)
d = d.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
return d
now = datetime.datetime.utcnow()
# next month
shiftmonth(now, 1)
# previous month
shiftmonth(now, -1)
# 从当前月份中获取星期几是哪天
def monthweekdays(month, weekday):
now = datetime.datetime.utcnow()
d = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
days = []
while d.month == month:
if d.isoweekday() == weekday:
days.append(d)
d += datetime.timedelta(days=1)
return days
monthweekdays(2,1)
python时间
于 2022-02-07 17:18:57 首次发布