Advertisement
cd62131

next nice datetime

Dec 20th, 2018
546
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import datetime
  3.  
  4.  
  5. def next_nice_datetime(dt, tzinfo=None):
  6.     tzinfo = datetime.timezone.utc if dt.tzinfo == datetime.timezone.utc else tzinfo
  7.     if dt.minute == 0 and dt.second == 0 and dt.microsecond == 0 and dt.hour in [
  8.             2, 10, 18
  9.     ]:
  10.         return dt.replace(tzinfo=tzinfo)
  11.     elif 18 <= dt.hour:
  12.         return (dt + datetime.timedelta(days=1)).replace(
  13.             hour=2, minute=0, second=0, microsecond=0, tzinfo=tzinfo)
  14.     elif 10 <= dt.hour:
  15.         return dt.replace(
  16.             hour=18, minute=0, second=0, microsecond=0, tzinfo=tzinfo)
  17.     elif 2 <= dt.hour:
  18.         return dt.replace(
  19.             hour=10, minute=0, second=0, microsecond=0, tzinfo=tzinfo)
  20.     else:
  21.         return dt.replace(
  22.             hour=2, minute=0, second=0, microsecond=0, tzinfo=tzinfo)
  23.  
  24.  
  25. for t1, t2 in [(dt, next_nice_datetime(dt)) for dt in [
  26.         datetime.datetime.utcnow(),
  27.         datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc),
  28.         datetime.datetime.strptime('20181221T020000.000000',
  29.                                    '%Y%m%dT%H%M%S.%f'),
  30.         datetime.datetime.strptime('20181221T020000.000001',
  31.                                    '%Y%m%dT%H%M%S.%f')
  32. ]]:
  33.     print('{} ---> {}'.format(t1, t2))
  34.  
  35. d = datetime.datetime.utcnow()
  36. print('{} ---> {}'.format(d, next_nice_datetime(
  37.     d, tzinfo=datetime.timezone.utc)))
  38.  
  39. for t1, t2 in [(dt, next_nice_datetime(dt)) for dt in [
  40.         datetime.datetime.strptime('20181221T{:02d}0123.456789'.format(s),
  41.                                    '%Y%m%dT%H%M%S.%f') for s in range(24)
  42. ]]:
  43.     print('{} ---> {}'.format(t1, t2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement