Python date With Examples

Python date class is part of datetime module.

Python date

Python date object represents a date (year, month and day) in a calendar. January 1 of year 1 is called day number 1, January 2 of year 1 is called day number 2, and so on.

We can create date instance using the following factory method.

All the arguments are mandatory and should be an integer in the valid range.

Year value should be in the range 1-9999, month should be in the range 1-12 and day should be in the range of valid days in the given month of the year.

If the argument forms an invalid date, then ValueError will be raised.

Python Create Date Instance

We can create date instance from the factory method.

Output: 2018-12-25

There are some class methods to create date instance too.

Create Today’s Date

Output: 2018-09-18

Create Date from Timestamp

Output:

Create Date from Ordinal

Output: 0002-01-01

Date from ISO String

A new method fromisoformat() has been added in Python 3.7 to create date instance from ISO format string. The input string should be in the format of YYYY-MM-DD.

Date Class Attributes

Output:

Date instance attributes

Date instance attributes are read only.

Output:

Date Operations with timedelta

Date object supports arithmetic operators with timedelta instance to create future and past dates.

Output:

Date instance methods

Let’s look at some date instance methods.

replace(year=self.year, month=self.month, day=self.day)

Returns a date instance with same value, unless its new value is provided through keyword arguments.

Output:

timetuple()

Return a time.struct_time instance, same as being returned by time.localtime().

Output:

Notice that hour, minutes and seconds value will always be 0 and DST flag will always be -1.

toordinal()

Returns the ordinal value of the date instance.

Output: 736955

weekday()

Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

Output: 1

isoweekday()

Return the day of the week as an integer, where Monday is 1 and Sunday is 7.

Output: 2

isocalendar()

Returns a tuple (ISO year, ISO week number, ISO weekday).

Output: (2018, 38, 2)

isoformat()

Return a string representing the date in ISO 8601 format i.e. “YYYY-MM-DD”.

Output: 2018-09-18

ctime()

Returns a string representing the date instance.

Output: Tue Sep 18 00:00:00 2018

Python Date to Formatted String

We can use strftime() function to convert date instance to string with specified formatting.

Output: 2018/09/18

Python Convert String to Date

We can use datetime strptime() function to convert string to datetime instance. Then we can use its date() function to convert to date instance.

Output:

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply