9 datetime Standard Library

This is a built-in library by Python. There is no need to install this library.

9.1 ISO8601

https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators

9.1.1 Date Time

UTC: "2007-04-05T14:30Z" #notice Z GMT+8: "2007-04-05T12:30+08:00 #notice +08:00 GMT+8: "2007-04-05T12:30+0800 #notice +0800 GMT+8: "2007-04-05T12:30+08 #notice +08

9.1.2 Date

2019-02-04 #notice no timezone available

9.2 Module Import

from datetime import date     # module for date object
from datetime import time     # module for time object
from datetime import datetime # module for datetime object
from datetime import timedelta

9.3 Class

datetime library contain three class of objects:
- date (year,month,day)
- time (hour,minute,second)
- datetime (year,month,day,hour,minute,second)
- timedelta: duration between two datetime or date object

9.4 date

9.4.1 Constructor

print( date(2000,1,1) )
#:> 2000-01-01
print( date(year=2000,month=1,day=1) )
#:> 2000-01-01
print( type(date(year=2000,month=1,day=1)))
#:> <class 'datetime.date'>

9.4.2 Class Method

9.4.2.1 today

This is local date (not UTC)

date.today()
#:> datetime.date(2020, 11, 20)
print( date.today() )
#:> 2020-11-20

9.4.2.2 Convert From ISO fromisoformat

strptime is not available for date conversion. It is only for datetime conversion

date.fromisoformat('2011-11-11')
#:> datetime.date(2011, 11, 11)

To convert non-iso format date string to date object, convert to datetime first, then to date

9.4.3 Instance Method

9.4.3.1 replace()

  • Replace year/month/day with specified parameter, non specified params will remain unchange.
  • Example below change only month. You can change year or day in combination
print( date.today() )
#:> 2020-11-20
print( date.today().replace(month=8) )
#:> 2020-08-20

9.4.3.2 weekday(), isoweekday()

For weekday(), Zero being Monday
For isoweekday(), Zero being Sunday

print( date.today().weekday() )
#:> 4
print( date.today().isoweekday() )
#:> 5
weekdays = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
wd = date.today().weekday()
print( date.today(), "is day", wd ,"which is", weekdays[wd] )
#:> 2020-11-20 is day 4 which is Fri

9.4.3.3 Formating with isoformat()

isoformat() return ISO 8601 String (YYYY-MM-DD)

date.today().isoformat() # return string
#:> '2020-11-20'

9.4.3.4 Formating with strftime

For complete directive, see below:
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

date.today().strftime("%m/%d")
#:> '11/20'

9.4.3.5 isocalendar()

isocalendar return a 3-tuple, (ISO year, ISO week number, ISO weekday).

date.today().isocalendar() ## return tuple 
#:> (2020, 47, 5)

9.4.4 Attributes

print( date.today().year )
#:> 2020
print( date.today().month )
#:> 11
print( date.today().day )
#:> 20

9.5 date and datetime

9.5.1 Constructor

import datetime as dt

print( 
    dt.date(2000,1,1,), '\n',
    dt.datetime(2000,1,1,0,0,0), '\n',
    dt.datetime(year=2000,month=1,day=1,hour=23,minute=15,second=55),'\n',
    type(dt.date(2000,1,1)),'\n',
    type(dt.datetime(2000,1,1,0,0,0)))
#:> 2000-01-01 
#:>  2000-01-01 00:00:00 
#:>  2000-01-01 23:15:55 
#:>  <class 'datetime.date'> 
#:>  <class 'datetime.datetime'>

9.5.2 Class Method

9.5.2.1 now and today

Both now() and today() return current system local datetime, no timezone

print(  dt.datetime.now(), '\n',
        dt.datetime.now().date())
#:> 2020-11-20 14:28:25.898918 
#:>  2020-11-20
dt.datetime.today()
#:> datetime.datetime(2020, 11, 20, 14, 28, 25, 906038)

9.5.2.2 utcnow

dt.datetime.utcnow()
#:> datetime.datetime(2020, 11, 20, 20, 28, 25, 916074)

9.5.2.3 combine() date and time

Apply datetime.combine() module method on both date and time object to get datetime

now = dt.datetime.now()
dt.datetime.combine(now.date(), now.time())
#:> datetime.datetime(2020, 11, 20, 14, 28, 25, 922861)

9.5.2.4 Convert from String strptime()

Use strptime to convert string into datetime object

%I : 12-hour
%H : 24-hour
%M : Minute
%p : AM/PM
%y : 18
%Y : 2018
%b : Mar
%m : month (1 to 12)
%d : day
datetime.strptime('2011-02-25','%Y-%m-%d')
#:> datetime.datetime(2011, 2, 25, 0, 0)
datetime.strptime('9-01-18','%d-%m-%y')
#:> datetime.datetime(2018, 1, 9, 0, 0)
datetime.strptime('09-Mar-2018','%d-%b-%Y')
#:> datetime.datetime(2018, 3, 9, 0, 0)
datetime.strptime('2/5/2018 4:49 PM', '%m/%d/%Y %I:%M %p')
#:> datetime.datetime(2018, 2, 5, 16, 49)

9.5.2.5 Convert from ISO fromisoformat

  • fromisoformat() is intend to be reverse of isoformat()
  • It actually not ISO compliance: when Z or +8 is included at the end of the string, error occur
#s = dt.datetime.now().isoformat()
dt.datetime.fromisoformat("2019-02-05T10:22:33")
#:> datetime.datetime(2019, 2, 5, 10, 22, 33)

9.5.3 Instance Method

9.5.3.1 weekday

datetime.now().weekday()
#:> 4

9.5.3.2 replace

datetime.now().replace(year=1999)
#:> datetime.datetime(1999, 11, 20, 14, 28, 25, 988527)

9.5.3.3 convert to .time()

datetime.now().time()
#:> datetime.time(14, 28, 25, 998462)

9.5.3.4 Convert to .date()

datetime.now().date()
#:> datetime.date(2020, 11, 20)

9.5.3.5 Convert to String

str

str( datetime.now() )
#:> '2020-11-20 14:28:26.024638'

Use strftime()

dt.datetime.now().strftime('%d-%b-%Y')
#:> '20-Nov-2020'
dt.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ')  ## ISO 8601 UTC
#:> '2020-11-20T20:28:26.048793Z'

Use isoformat()

dt.datetime.utcnow().isoformat()
#:> '2020-11-20T20:28:26.056107'

9.5.4 Attributes

print( datetime.now().year )
#:> 2020
print( datetime.now().month )
#:> 11
print( datetime.now().day )
#:> 20
print( datetime.now().hour )
#:> 14
print( datetime.now().minute )
#:> 28

9.6 time

9.6.1 Constructor

print( time(2) )    #default single arugement, hour
#:> 02:00:00
print( time(2,15) ) #default two arguments, hour, minute
#:> 02:15:00
print( time(hour=2,minute=15,second=30) )
#:> 02:15:30

9.6.2 Class Method

9.6.2.1 now()

There is unfortunately no single function to extract the current time. Use time() function of an datetime object

datetime.now().time()
#:> datetime.time(14, 28, 26, 105177)

9.6.3 Attributes

print( datetime.now().time().hour )
#:> 14
print( datetime.now().time().minute )
#:> 28
print( datetime.now().time().second )
#:> 26

9.7 timedelta

  • years argument is not supported
  • Apply timedelta on datetime object
  • timedelta cannot be applied on time object , because timedelta potentially go beyond single day (24H)
delt = timedelta(days=365,minutes=33,seconds=15)
now = datetime.now()
print ('delt+now : ', now+delt)
#:> delt+now :  2021-11-20 15:01:41.137995