Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to date object without time info

Tags:

python

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?

like image 879
SaeX Avatar asked Apr 27 '14 13:04

SaeX


People also ask

How do you convert a date without time in Python?

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'.

How do I turn a string into a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do you convert string to UTC time in Python?

Python convert a string to datetime with timezone In this example, I have imported a module called timezone. datetime. now(timezone('UTC')) is used to get the present time with timezone. The format is assigned as time = “%Y-%m-%d %H:%M:%S%Z%z”.


1 Answers

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
like image 138
Ffisegydd Avatar answered Oct 08 '22 14:10

Ffisegydd