Python datetime date() Method with Example

Python datetime.date() Method: In this tutorial, we will learn about the date() method of datetime class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 22, 2023

Python datetime.date() Method

The datetime.date() method is used convert the datetime object into a date object with the same year, month and day. We require an instance of datetime class as it is an instance method.

Module

The following module is required to use date() method:

import datetime

Class

The following class is required to use date() method:

from datetime import datetime

Syntax

The following is the syntax of date() method:

date()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is a date object with year, month and day value same as that of the given datetime object.

Example to Convert datetime Object to date Object in Python

## Creating a date object from a datetime object
from datetime import datetime

## Creating datetime instance
x = datetime(2020, 3, 4,23,12,23,44)
d = x.date()
print("Original object:", x)
print("New date object:",d)
print()

x = datetime.now()
d = x.date()
print("Original date and time", x)
print("New date objec:", d)
print()

x = datetime.today()
d = x.date()
print("Printing the same")
print(x)
print(d)

Output

Original object: 2020-03-04 23:12:23.000044
New date object: 2020-03-04

Original date and time 2020-05-03 17:08:13.516192
New date objec: 2020-05-03

Printing the same
2020-05-03 17:08:13.517060
2020-05-03



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.