How do I convert a datetime to date?


How do I convert a datetime.datetime object (e.g., the return value of to a object in Python?

Asked By: niklasfi



From the documentation:

Return date object with same year, month and day.

Answered By: user395760

Use the date() method:
Answered By: ars

You use the method:

Obviously, the expression above can (and should IMHO 🙂 be written as:
Answered By: tzot

You can convert a datetime object to a date with the date() method of the date time object, as follows:

Answered By: Furbeenator
import time
import datetime

# use mktime to step by one day
# end - the last day, numdays - count of days to step back
def gen_dates_list(end, numdays):
  start = end - datetime.timedelta(days=numdays+1)
  end   = int(time.mktime(end.timetuple()))
  start = int(time.mktime(start.timetuple()))
  # 86400 s = 1 day
  return xrange(start, end, 86400)

# if you need reverse the list of dates
for dt in reversed(gen_dates_list(, 100)):
    print datetime.datetime.fromtimestamp(dt).date()
Answered By: Serenity

you could enter this code form for (today date & Names of the Day & hour) :'%y-%m-%d %a %H:%M:%S')

’19-09-09 Mon 17:37:56′

and enter this code for (today date simply):'%y-%m-%d')


for object :

Answered By: kamran26

Answer updated to Python 3.7 and more

Here is how you can turn a date-and-time object

(aka datetime.datetime object, the one that is stored inside models.DateTimeField django model field)

into a date object (aka object):

from datetime import datetime

#your date-and-time object
# let's supposed it is defined as
datetime_element = datetime(2020, 7, 10, 12, 56, 54, 324893)

# where
# datetime_element = datetime(year, month, day, hour, minute, second, milliseconds)

# WHAT YOU WANT: your date-only object
date_element =

And just to be clear, if you print those elements, here is the output :


2020-07-10 12:56:54.324893



Answered By: Tms91

I use data.strftime('%y-%m-%d') with lambda to transfer column to date

Answered By: Wei Chun Chang
Solved: AttributeError: 'Series' object has no attribute 'date'

You can use as below,

df["date"] = pd.to_datetime(df["date"])

where in above code date contains both date and time (2020-09-21 22:32:00), using above code we can get only date as (2020-09-21)

Answered By: Manjula Devi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.