18

I'd like to convert a string to a Python date-object. I'm using d = datetime.strptime("25-01-1973", "%d-%m-%Y"), as per the documentation on https://docs.python.org/2/library/datetime.html, and that yields datetime.datetime(1973, 1, 25, 0, 0).

When I use d.isoformat(), I get '1973-01-25T00:00:00', but I'd like to get 1973-01-25 (without the time info) as per the docs:

date.isoformat()
Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’. For example, date(2002, 12, 4).isoformat() == '2002-12-04'.

It is understood I can use SimpleDateFormat etc., but since the isoformat() example is explicitly mentioned in the docs, I'm not sure why I'm getting the unwanted time info after the date.

I guess I'm missing a detail somewhere?

SaeX
  • 17,240
  • 16
  • 77
  • 97

1 Answers1

25

The object that is returned by datetime.datetime.strptime is a datetime.datetime object rather than a datetime.date object. As such it will have the time information included and when isoformat() is called will include this information.

You can use the datetime.datetime.date() method to convert it to a date object as below.

import datetime as dt

d = dt.datetime.strptime("25-01-1973", "%d-%m-%Y")

# Convert datetime object to date object.
d = d.date()

print(d.isoformat())
# 1973-01-25
Community
  • 1
  • 1
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125