utils.py 637 B

1234567891011121314151617181920212223242526272829303132
  1. from calendar import timegm
  2. from datetime import datetime
  3. from django.conf import settings
  4. from django.utils.functional import lazy
  5. from django.utils.timezone import is_naive, make_aware, utc
  6. def make_utc(dt):
  7. if settings.USE_TZ and is_naive(dt):
  8. return make_aware(dt, timezone=utc)
  9. return dt
  10. def aware_utcnow():
  11. return make_utc(datetime.utcnow())
  12. def datetime_to_epoch(dt):
  13. return timegm(dt.utctimetuple())
  14. def datetime_from_epoch(ts):
  15. return make_utc(datetime.utcfromtimestamp(ts))
  16. def format_lazy(s, *args, **kwargs):
  17. return s.format(*args, **kwargs)
  18. format_lazy = lazy(format_lazy, str)