Python date

Filed Under: Python

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.


datetime.date(year, month, day)

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.


from datetime import date

d = date(2018, 12, 25)

print(d)

Output: 2018-12-25

There are some class methods to create date instance too.

Create Today’s Date


d = date.today()
print(d)

Output: 2018-09-18

Create Date from Timestamp


import time
t = time.time()
print(t)
d = date.fromtimestamp(t)
print(d)
d = date.fromtimestamp(1537261418)
print(d)

Output:


1537265122.553337
2018-09-18
2018-09-18

Create Date from Ordinal


d = date.fromordinal(366)
print(d)

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 from ISO string format, added in Python 3.7
d = date.fromisoformat('2018-09-19')
print(d)

Date Class Attributes


print(date.min)
print(date.max)
print(date.resolution)

Output:


0001-01-01
9999-12-31
1 day, 0:00:00

Date instance attributes

Date instance attributes are read only.


d = date.today()
print(d.year)
print(d.month)
print(d.day)

Output:


2018
9
18

Date Operations with timedelta

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


date_tomorrow = date.today() + timedelta(days=1)
print(date_tomorrow)
date_yesterday = date.today() - timedelta(days=1)
print(date_yesterday)

td = date_tomorrow - date_yesterday
print(td)

print(date_tomorrow > date_yesterday)

Output:


2018-09-19
2018-09-17
2 days, 0:00:00
True

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.


today = date.today()
print(today)
new_date = today.replace(year=2020)
print(new_date)

Output:


2018-09-18
2020-09-18

timetuple()

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


print(today.timetuple())

Output:


time.struct_time(tm_year=2018, tm_mon=9, tm_mday=18, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=261, tm_isdst=-1)

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.


print(today.toordinal())

Output: 736955

weekday()

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


print(today.weekday()) # 2018-09-18 is Tuesday

Output: 1

isoweekday()

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


print(today.isoweekday())

Output: 2

isocalendar()

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


print(today.isocalendar())

Output: (2018, 38, 2)

isoformat()

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


print(today.isoformat())

Output: 2018-09-18

ctime()

Returns a string representing the date instance.


print(today.ctime())

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.


print(today.strftime('%Y/%m/%d'))

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.


from datetime import datetime
dt = datetime.strptime('2018/09/18', '%Y/%m/%d').date()
print(type(dt))
print(dt)

Output:


<class 'datetime.date'>
2018-09-18
You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages