What is Python module for date manipulation?

PythonServer Side ProgrammingProgramming

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


This will give you the output:

$ python datetime_time.py
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


This will give the output:

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.

Published on 20-Dec-2017 13:16:13