Wednesday, August 15, 2018

Python Date/Time modules


`datetime`
Can provide time difference calculations

>>> # dates are easily constructed and formatted
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368

Using strptime()

>>> from datetime import datetime
>>>
>>> datetime.strptime('2016-01-01', '%Y-%m-%d')
datetime.datetime(2016, 1, 1, 0, 0)
>>>
>>> datetime.strptime('03-01-2018', '%Y-%m-%d')
Traceback (most recent call last):
  File "", line 1, in
  File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime
(data_string, format))
ValueError: time data '03-01-2018' does not match format '%Y-%m-%d'
>>>
>>>
>>> datetime.strptime('2016-01-01', '%Y-%m-%d %H:%M:%S')
Traceback (most recent call last):
  File "", line 1, in
  File "/usr/lib/python2.7/_strptime.py", line 332, in _strptime
(data_string, format))
ValueError: time data '2016-01-01' does not match format '%Y-%m-%d %H:%M:%S'
>>>
>>> datetime.strptime('2016-01-01 04:16:34', '%Y-%m-%d %H:%M:%S')
datetime.datetime(2016, 1, 1, 4, 16, 34)        
>>>


Managing time differences

>>> a = timedelta(days=365)
>>> b = timedelta(days=100)
>>> a - b
datetime.timedelta(265)
>>>

Callable methods on datetime

>>> date = datetime.strptime('2018-03-18', '%Y-%m-%d')
>>>
>>> dir(date)
['add', 'class', 'delattr', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'ne', 'new', 'radd', 'reduce', 'reduce_ex', 'repr', 'rsub', 'setattr', 'sizeof', 'str', 'sub', 'subclasshook', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']
>>>
>>> date.timestamp()
1521302400.0
>>>

`time`
Can do simple time operations and also include a sleep function.
>>> import time
>>> dir(time)
['CLOCK_MONOTONIC', 'CLOCK_MONOTONIC_RAW', 'CLOCK_PROCESS_CPUTIME_ID', 'CLOCK_REALTIME', 'CLOCK_THREAD_CPUTIME_ID', '_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'clock_getres', 'clock_gettime', 'clock_settime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']
>>> time.localtime
>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=8, tm_mday=29, tm_hour=18, tm_min=20, tm_sec=35, tm_wday=1, tm_yday=241, tm_isdst=0)
>>>
>>>
>>>
>>> time.sleep(3)
>>>
`timeit`
Measures speed of small code snippets.
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791

For larger codes, use `profile` and `pstats`

No comments:

Post a Comment