Python Basic date and time types


To manipulate dates and times in the python there is a module called datetime. There are two types of date and time objects. The types are naïve and the aware.

In the naïve object, there is no enough information to unambiguously locate this object from other date-time objects. In this approach it uses Coordinate Universal Time (UTC).

In the aware type objects there are different information regarding algorithmic and political time adjustments. This type of objects is used to represent some specific time moments.

To use this module, we should import it using −

import datetime

There are different classes, constants and methods in this module.

The constants are −

Sr.No. Constant & Description
1

datetime.MINYEAR

It is the smallest Year number, which can be applied as date or datetime objects. The value is 0

2

datetime.MAXYEAR

It is the largest Year number, which can be applied as date or datetime objects. The value is 9999

The Available datatypes are −

Sr.No. Datatypes & Description
1

date

It is date type object. It uses Gregorian calendar. It has year, month, day attributes.

2

time

It is a time object class. It is independent of any particular day. It has hour, minute, second, microsecond and tzinfo attributes.

3

datetime

It is a combined set of dates and times.

4

timedelta

It is used to express the difference between two date, time or datetime values in milliseconds.

5

tzinfo

It is an Abstract Base Class. It holds the time zone information. It is used by the datetime and time classes.

6

timezone

In this class, it implements tzinfo. There is a fixed offset from the UTC

Date Type Object

The date objects represent a date. In the date there are Day, month and the Year part. It uses the Gregorian Calendar. According to this calendar the day of January 1 of Year 1 is called as the day number 1, and so on.

Some date related methods are −

Method date.date(year, month, day)

This is the constructor to create a date type object. To create a date, all arguments are required as integer type data. The year must be in range MINYEAR & MAXYEAR. If the given date is not valid, it will raise ValueError.

Method date.today()

This method is used to return the current local date.

Method date.fromtimestamp(timestamp)

This method is used to get the date from POSIX timestamp. If the timestamp value is out of range, it will raise OverflowError.

Method date.fromordinal(ordinal)

This method is used to get the date from proleptic Gregorian Calendar ordinal. It is used to get the date from the date count from January 1 of Year 1.

Method date.toordinal()

This method is used to return a date to proleptic Gregorian Calendar ordinal.

Method date.weekday()

This method is used to return the date of a week as an integer from the date. The Monday is 0, Tuesday is 1 and so on.

Method date.isoformat()

This method is used to return the date as an ISO 8601 format string. The format is YYYY-MM-DD.

Example Code

Live Demo

import datetime as dt
new_date = dt.date(1998, 9, 5) #Store date 5th septemberm, 1998
print("The Date is: " + str(new_date))
print("Ordinal value of given date: " + str(new_date.toordinal()))
print("The weekday of the given date: " + str(new_date.weekday())) #Monday is 0
my_date = dt.date.fromordinal(732698) #Create a date from the Ordinal value.
print("The Date from ordinal is: " + str(my_date))
td = my_date - new_date #Create a timedelta object
print('td Type: ' + str(type(td)) + '\nDifference: ' + str(td))

Output

The Date is: 1998-09-05
Ordinal value of given date: 729637
The weekday of the given date: 5
The Date from ordinal is: 2007-01-22
td Type: <class 'datetime.timedelta'>
Difference: 3061 days, 0:00:00

Time Object

The time object represents a local time. In the time there are hour, minute second, microsecond, tzinfo part. The hour will be in range 0 to 24 and the minute and second will be in range 0 to 60, and microseconds will be in range 0 to 1000000.

Some time related methods are

Method time.fromisoformat(time_string)

This method is used to get time from an ISO 8601 string. It can take any of the output of time.isoformat() method.

Method time.replace(hour = self.hour, minute = self.minute, second = self.second, microsecond = self.microseconds, tzinfo = self.tzinfo, *fold=0)

This method is used to return a time by taking values from the arguments. If no argument is passed, it will return the same time object values.

Method time.tzname()

This method is used to return the name of the time zone. If the tzinfo is None, it will return None.

Datetime Object

The datetime object holds both date and time. As date object, it supports Gregorian Calendar and as Time object it holds exactly 3600*24 seconds for each day.

It supports all date and time related methods, some methods are also present for datetime. These are like −

Method datetime.now(tz=None)

This method is used to get the current date and time. If the tz is not present or None, then, it will return date like the today() method.

Method datetime.utcnow()

This method is used to get the current UTC date and time related information.

There are another two methods called strftime() and strptime(). These methods are applicable for both date and time objects, as well as datetime objects.

Method datetime.strftime(format[, t])

The method strftime() converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. format must be a string. An exception ValueError is raised if any field in t is outside of the allowed range.

Method datetime.strftime(format[, t])

The method strptime() parses a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime(). The format parameter uses the same directives as those used by strftime(); it defaults to "%a %b %d %H:%M:%S %Y" which matches the formatting returned by ctime().

These two methods use some directives. Some of them are listed below −

Sr.No. Directives & Description
1

%A

Full Weekday name

2

%B

Full Month Name

3

%d

Day of the month (0 to 31)

4

%S

Second

5

%G

4 digit Year, corresponding to ISO week number

6

%m

Month (1 to 12)

7

%M

Minute

8

%T

Current time, equal to %H:%M:%S

9

%W

Week number of the current year, starting with the first Monday as the first day of the first week

10

%w

Day of the week as a decimal, Sunday=0

11

%Y

Year including the century

12

%Z or %z

Time zone or name or abbreviation

Example Code

Live Demo

import datetime as dt
my_date1 = dt.datetime(2015, 1, 4) #Storing the date 4th Jan, 2015
print(my_date1)
print('The Weekday of that day was: ' + my_date1.strftime('%A'))
my_date2 = dt.datetime.strptime('August-15-2017', '%B-%d-%Y') #Storing the date 15th Aug, 2017
print(my_date2)
print('The Weekday of that day was: ' + my_date2.strftime('%A'))
print('The difference between two days: ' + str(abs(my_date1 - my_date2)))

Output

2015-01-04 00:00:00
The Weekday of that day was: Sunday
2017-08-15 00:00:00
The Weekday of that day was: Tuesday
The difference between two days: 954 days, 0:00:00

Updated on: 30-Jul-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements