2020-07-09 07:41:02 +00:00
|
|
|
import pytz
|
2022-11-26 11:07:12 +00:00
|
|
|
from datetime import datetime, timedelta, timezone
|
2020-07-09 07:41:02 +00:00
|
|
|
from django.utils import timezone as dj_timezone
|
|
|
|
from rest_framework.fields import DateTimeField
|
|
|
|
|
2022-11-26 11:07:12 +00:00
|
|
|
max = datetime.max.replace(tzinfo=timezone.utc)
|
2020-07-09 07:41:02 +00:00
|
|
|
|
|
|
|
|
2022-11-26 11:07:12 +00:00
|
|
|
def astimezone(dt: datetime, tzinfo: pytz.tzinfo.DstTzInfo):
|
2020-07-09 07:41:02 +00:00
|
|
|
assert dj_timezone.is_aware(dt)
|
|
|
|
return tzinfo.normalize(dt.astimezone(tzinfo))
|
|
|
|
|
|
|
|
|
2022-11-26 11:07:12 +00:00
|
|
|
def as_china_cst(dt: datetime):
|
2020-07-09 07:41:02 +00:00
|
|
|
return astimezone(dt, pytz.timezone('Asia/Shanghai'))
|
|
|
|
|
|
|
|
|
2022-11-26 11:07:12 +00:00
|
|
|
def as_current_tz(dt: datetime):
|
2020-07-09 07:41:02 +00:00
|
|
|
return astimezone(dt, dj_timezone.get_current_timezone())
|
|
|
|
|
|
|
|
|
2021-10-20 11:45:37 +00:00
|
|
|
def utc_now():
|
2020-07-09 07:41:02 +00:00
|
|
|
return dj_timezone.now()
|
|
|
|
|
|
|
|
|
2021-10-20 11:45:37 +00:00
|
|
|
def local_now():
|
2021-10-26 02:52:23 +00:00
|
|
|
return dj_timezone.localtime(dj_timezone.now())
|
2020-07-09 07:41:02 +00:00
|
|
|
|
|
|
|
|
2021-10-22 12:06:16 +00:00
|
|
|
def local_now_display(fmt='%Y-%m-%d %H:%M:%S'):
|
|
|
|
return local_now().strftime(fmt)
|
|
|
|
|
|
|
|
|
2022-05-09 08:37:31 +00:00
|
|
|
def local_now_date_display(fmt='%Y-%m-%d'):
|
|
|
|
return local_now().strftime(fmt)
|
|
|
|
|
|
|
|
|
2022-11-26 11:07:12 +00:00
|
|
|
def local_zero_hour(fmt='%Y-%m-%d'):
|
|
|
|
return datetime.strptime(local_now().strftime(fmt), fmt)
|
|
|
|
|
|
|
|
|
|
|
|
def local_monday():
|
|
|
|
zero_hour_time = local_zero_hour()
|
|
|
|
return zero_hour_time - timedelta(zero_hour_time.weekday())
|
|
|
|
|
|
|
|
|
2020-07-09 07:41:02 +00:00
|
|
|
_rest_dt_field = DateTimeField()
|
|
|
|
dt_parser = _rest_dt_field.to_internal_value
|
2021-10-20 11:45:37 +00:00
|
|
|
dt_formatter = _rest_dt_field.to_representation
|