datetime

Examples

Create a datetime object

Attributes: datetime.datetime(year, month, day, hour, minute, second, microsecond)

Example:

>>> today = datetime.datetime.today()
>>> today
datetime.datetime(2018, 7, 31, 21, 24, 28, 194922)

Timedeltas

“Using replace() is not the only way to calculate future/past dates. You can use datetime to perform basic arithmetic on date values via the timedelta class. Subtracting dates produces a timedelta, and a timedelta can be added or subtracted from a date to produce another date. The internal values for a timedelta are stored in days, seconds, and microseconds.” (see: https://pymotw.com/2/datetime/)

Date math uses the standard arithmetic operators. This example with date objects illustrates using timedelta objects to compute new dates, and subtracting date instances to produce timedeltas (including a negative delta value).

    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

print 'tomorrow - yesterday:', tomorrow - yesterday
print 'yesterday - tomorrow:', yesterday - tomorrow
$ python datetime_date_math.py

Today    : 2013-02-21
One day  : 1 day, 0:00:00
Yesterday: 2013-02-20
Tomorrow : 2013-02-22
tomorrow - yesterday: 2 days, 0:00:00
yesterday - tomorrow: -2 days, 0:00:00