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?
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'.
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.
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”.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With