Date and Time functions

The datetime , time and calendar modules provides functions and classes for manipulating dates and times. However for general purpose parsing, formatting and arithmetic, we only use datetime module. You will learn only the datetime module and time function of the time module in this lesson. We typically use date and datetime objects from datetime module for most of the date manipulations.

  • A date object from datetime module represents a date (year, month and day) in a Gregorian calendar.
  • A datetime object represents both date and time.
import datetime
today = datetime.date.today()
now = datetime.datetime.now()
print(today)
print(now)

Output:

Date and time when this program is run in yyyy-mm-dd format for date and yyyy-mm-dd hours:minutes:seconds format for datetime

Above program prints out date and time when the program is run. You can format the display using strftime function. Also you can import just datetime and date from datetime module instead of importing all the functions and classes from datetime. Here is the modified program

from datetime import datetime
from datetime import date

today = date.today() # no need of datetime prefix due to date getting a namespace in import
now = datetime.now()
print(today.strftime("%m/%d/%Y"))
print(now.strftime("%m/%d/%Y %H:%M"))

Output:

Prints out the date, datetime in the given format of month/day/year for date part and for the time part it removes the seconds value.

Few routinely used formatting codes.

Code Description Example
%y 2-digit year 99
%Y 4-digit year 1999
%H Hour in 24 hour format 13
%I Hour in 12 hour format 02
%B Month name in full March
%b Abbreviated month name Mar
%A Full weekday name Friday
%a Abbreviated weekday name Fri

Create new date objects:

Python provides many constructors to create a date, datetime object from a string.

What is a constructor

A constructor in object oriented programming is a structure similar to a function which when invoked by sending in required parameters will return an object of the type that the contructor belongs to. Using date constructor we create date objects. Similarly using constructor for datetime you construct a datetime object.

Create datetime object

Using constructors for datetime and date, you can create respective objects from strings. datetime type can be either naive or aware. naive objects do not hold the timezone information. But since date object does not hold time information, date object does not have an aware version

datetime(year, month, day [,hour][,min][,sec][,microsec]) - datetime naive constructor

datetime (year, month, day [,hour][,min][,sec][,microsec][,tzinfo]) - datetime aware constructor (with timezone)

Reference the official documentation for tzinfo: https://docs.python.org/3/library/datetime.html#tzinfo-objects

If you have to create a datetime for a log entry on Oct 1st 1990, you would do so with below code:

log_entry = date(1990,10,1)

Parsing String to Datetime object

str method converts a String to Date object. Here is an example

from datetime import datetime
oneday = datetime(2018, 1, 17)
str(oneday)

Output:
'2018-01-17 00:00:00'

strptime method can be applied to parse a string which represents date and time, into a date object using multiple formats. Here are the different ways you could parse the strings which represent date/time in many formats, to get the same datetime object value.

from datetime import datetime
datetime.strptime("01/10/1990 12:10:03", "%d/%m/%Y %H:%M:%S")
datetime.strptime("01 10 1990 12-10-03", "%d %m %Y %H-%M-%S")
datetime.strptime("01 10 1990 12 10 03", "%d %m %Y %H %M %S")

# Another way of invoking strftime
oneday = datetime(2018, 1, 17)
oneday.strftime('%Y-%m-%d')

Output:
'2018-01-17 00:00:00'

You can get various parts of the date/datetime by accessing its attributes.

from datetime import datetime
from datetime import date

log_entry = datetime(1990,10,1,12,10,3)
print(log_entry)

print(log_entry.month)  # Outputs 10
print(log_entry.year)   # Outputs 1990
print(log_entry.day)    # Outputs 1
print(log_entry.hour)   # Outputs 12
print(log_entry.minute) # Outputs 10
print(log_entry.second) # Outputs 3

Output:

1990-10-01 12:10:03
10
1990
1
12
10
3

Official reference

Time Delta

Time delta represents difference between two datetime objects. Here is an example


from datetime import datetime
delta = datetime(2018, 3, 31) - datetime(2018, 3, 1, 8, 15)
print(type(delta))

print(delta.days)
print(delta.seconds)

Output:
<class 'datetime.timedelta'>
29
56700

The output prints out the datatype of the difference which is timedelta and the difference in days and seconds between March 31st 0 hours to March 1st 8 hours and 15 minutes. You can add/subtract one or multiples of timedelta objects to any date object and get a new shifted date object.

Time objects

While the datetime module also provides time object, we mostly use time function from time module for routine tasks of clocking an event like the amount of time lapsed for executing one or more statements or a program. Time provides unix time stamps; expressed as a floating point number representing seconds from unix epoch time.

The time constructor of the datetime module is used for constructing a specific time and in this module you also get the ability to set timezone with the tzinfo object. Below you see examples of using both:


from datetime import time as t
import time

starttime = time.time()
noon = t(12, 10, 30)
print(noon.hour, noon.minute, noon.second)
endtime = time.time()
print(endtime - starttime)

Output:
12 10 30
0.0006449222564697266

The second output above is the time it took to run the two statements between the startime and the endtime.

results matching ""

    No results matching ""