Python has a built-in module, datetime which includes functions and classes for doing date and time parsing, formatting, and arithmetic. Time values are represented using time class. It has the attributes for hour, minute, second, and microsecond. They can also include time zone information.
For example
import datetime t = datetime.time(1, 2, 3) print t print 'hour :', t.hour print 'minute:', t.minute print 'second:', t.second print 'microsecond:', t.microsecond print 'tzinfo:', t.tzinfo
Output
This will give you the output:
$ python datetime_time.py 01:02:03 hour : 1 minute: 2 second: 3 microsecond: 0 tzinfo: None
A time instance only holds values of the time and not a date associated with the time.
Calendar date values are represented with the date class. Instances have attributes for a year, month, and day. It is easy to create a date representing today’s date using the today() class method.
For example
import datetime today = datetime.date.today() print today print 'ctime:', today.ctime() print 'tuple:', today.timetuple() print 'ordinal:', today.toordinal() print 'Year:', today.year print 'Mon :', today.month print 'Day :', today.day
Output
This will give the output:
2017-09-07 ctime: Thu Sep 7 00:00:00 2017 tuple: time.struct_time(tm_year=2017, tm_mon=9, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=250, tm_isdst=-1) ordinal: 736579 Year: 2017 Mon : 9 Day : 7
You can read about the datetime module: https://pymotw.com/2/datetime/. The datetime module is pretty basic and can't handle more advanced stuff. You're better off using dateutil(https://dateutil.readthedocs.io/en/stable/) if you want features like Computing of relative deltas (next month, next year, next monday, last week of month, etc), Computing of relative deltas between two given date and/or datetime objects, etc.