datetime contains functions and classes for working with dates and times, separately and together.

Times


In [1]:
import datetime
t = datetime.time(1,2,3)
print(t)
print('Hour     :', t.hour)
print('Minute   :', t.minute)
print('Second   :', t.second)
print('microseond :', t.microsecond)
print('tzinof', t.tzinfo)


01:02:03
Hour     : 1
Minute   : 2
Second   : 3
microseond : 0
tzinof None

In [2]:
import datetime
print('Earliest    :', datetime.time.min)
print('Later       :', datetime.time.max)
print('Resolution  :', datetime.time.resolution)


Earliest    : 00:00:00
Later       : 23:59:59.999999
Resolution  : 0:00:00.000001

Dates


In [3]:
import datetime

today = datetime.date.today()
print(today)
print('ctime  :', today.ctime())
tt = today.timetuple()
print('tuple  : tm_year  =', tt.tm_year)
print('         tm_mon   =', tt.tm_mon)
print('         tm_mday  =', tt.tm_mday)
print('         tm_hour  =', tt.tm_hour)
print('         tm_min   =', tt.tm_min)
print('         tm_sec   =', tt.tm_sec)
print('         tm_wday  =', tt.tm_wday)
print('         tm_yday  =', tt.tm_yday)
print('         tm_isdst =', tt.tm_isdst)
print('ordinal:', today.toordinal())
print('Year   :', today.year)
print('Mon    :', today.month)
print('Day    :', today.day)


2017-09-02
ctime  : Sat Sep  2 00:00:00 2017
tuple  : tm_year  = 2017
         tm_mon   = 9
         tm_mday  = 2
         tm_hour  = 0
         tm_min   = 0
         tm_sec   = 0
         tm_wday  = 5
         tm_yday  = 245
         tm_isdst = -1
ordinal: 736574
Year   : 2017
Mon    : 9
Day    : 2

In [4]:
import datetime
import time
o = 733114
print('o    :',o)
print('fromordinal(o) :', datetime.date.fromordinal(o))


o    : 733114
fromordinal(o) : 2008-03-13

In [5]:
t = time.time()
print('t     :', t)
print('fromtimestamp(t)', datetime.date.fromtimestamp(t))


t     : 1504357272.7474
fromtimestamp(t) 2017-09-02

In [7]:
import datetime
print('Earliest:', datetime.date.min)
print('Latest:', datetime.date.max)
print('Resolution:', datetime.date.resolution)


Earliest: 0001-01-01
Latest: 9999-12-31
Resolution: 1 day, 0:00:00

timeDeltas


In [8]:
import datetime

print('microseconds:', datetime.timedelta(microseconds=1))
print('milliseconds:', datetime.timedelta(milliseconds=1))
print('seconds     :', datetime.timedelta(seconds=1))
print('minutes     :', datetime.timedelta(minutes=1))
print('hours       :', datetime.timedelta(hours=1))
print('days        :', datetime.timedelta(days=1))
print('weeks       :', datetime.timedelta(weeks=1))


microseconds: 0:00:00.000001
milliseconds: 0:00:00.001000
seconds     : 0:00:01
minutes     : 0:01:00
hours       : 1:00:00
days        : 1 day, 0:00:00
weeks       : 7 days, 0:00:00

In [9]:
import datetime

for delta in [datetime.timedelta(microseconds=1),
              datetime.timedelta(milliseconds=1),
              datetime.timedelta(seconds=1),
              datetime.timedelta(minutes=1),
              datetime.timedelta(hours=1),
              datetime.timedelta(days=1),
              datetime.timedelta(weeks=1),
              ]:
    print('{:15} = {:8} seconds'.format(
        str(delta), delta.total_seconds())
    )


0:00:00.000001  =    1e-06 seconds
0:00:00.001000  =    0.001 seconds
0:00:01         =      1.0 seconds
0:01:00         =     60.0 seconds
1:00:00         =   3600.0 seconds
1 day, 0:00:00  =  86400.0 seconds
7 days, 0:00:00 = 604800.0 seconds

Date Arithmetic


In [11]:
import datetime
today = datetime.date.today()
print('today :', today)
one_day = datetime.timedelta(days=1)
print('One day', one_day)
yesterday = today - one_day
print('Yesterday', yesterday)
tomorrow = today + one_day
print('Tomorrow', tomorrow)


today : 2017-09-02
One day 1 day, 0:00:00
Yesterday 2017-09-01
Tomorrow 2017-09-03

In [12]:
import datetime

one_day = datetime.timedelta(days=1)
print('1 day    :', one_day)
print('5 days   :', one_day * 5)
print('1.5 days :', one_day * 1.5)
print('1/4 day  :', one_day / 4)

# assume an hour for lunch
work_day = datetime.timedelta(hours=7)
meeting_length = datetime.timedelta(hours=1)
print('meetings per day :', work_day / meeting_length)


1 day    : 1 day, 0:00:00
5 days   : 5 days, 0:00:00
1.5 days : 1 day, 12:00:00
1/4 day  : 6:00:00
meetings per day : 7.0

Comparsion


In [14]:
import datetime
import time

print('Times:')
t1 = datetime.time(12, 55, 0)
print('  t1:', t1)
t2 = datetime.time(13, 5, 0)
print('  t2:', t2)
print('  t1 < t2:', t1 < t2)

print()
print('Dates:')
d1 = datetime.date.today()
print('  d1:', d1)
d2 = datetime.date.today() + datetime.timedelta(days=1)
print('  d2:', d2)
print('  d1 > d2:', d1 > d2)


Times:
  t1: 12:55:00
  t2: 13:05:00
  t1 < t2: True

Dates:
  d1: 2017-09-02
  d2: 2017-09-03
  d1 > d2: False

Combining Dates and Times


In [15]:
import datetime

print('Now    :', datetime.datetime.now())
print('Today  :', datetime.datetime.today())
print('UTC Now:', datetime.datetime.utcnow())
print()

FIELDS = [
    'year', 'month', 'day',
    'hour', 'minute', 'second',
    'microsecond',
]

d = datetime.datetime.now()
for attr in FIELDS:
    print('{:15}: {}'.format(attr, getattr(d, attr)))


Now    : 2017-09-02 21:08:11.244852
Today  : 2017-09-02 21:08:11.245200
UTC Now: 2017-09-02 13:08:11.246288

year           : 2017
month          : 9
day            : 2
hour           : 21
minute         : 8
second         : 11
microsecond    : 248471

Formatting


In [17]:
import datetime

format = "%a %b %d %H:%M:%S %Y"

today = datetime.datetime.today()
print('ISO     :', today)

s = today.strftime(format)
print('strftime:', s)

d = datetime.datetime.strptime(s, format)
print('strptime:', d.strftime(format))


ISO     : 2017-09-02 21:09:33.980646
strftime: Sat Sep 02 21:09:33 2017
strptime: Sat Sep 02 21:09:33 2017