Datetime strptime in python
import datetime
str_time= "2018-06-03 08:00:00"
date_date = datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")
print date_date
datetime.strptime(date_string, format)
function returns a datetime
object corresponding to date_string
, parsed according to format
.
When you print datetime
object, it is formatted as a string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS
References:
- https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime
- https://docs.python.org/2/library/datetime.html#datetime.datetime.isoformat
As astutely noted in the comments, you are parsing to a datetime object using the format you specified.
strptime(...)
is String Parse Time. You have specified the format for how the string should be interpreted to initialize a Datetime object, but that format is only utilized for initialization. By default, when you go to print that datetime object, you are getting the representation of str(DatetimeObjectInstance)
(in your case, str(d)
).
If you want a different format, you should use String Format Time (strftime(...)
)
You need to make sure you provide input accordingly
datetime.strptime(date_string,date_string_format).strftime(convert_to_date_string_format)
To print the date in specified format you need to provide format as below.
import datetime
d =datetime.datetime.strptime("01/27/2012","%m/%d/%Y").strftime('%m/%d/%Y')
print d
Output:
01/27/2012
>>Demo<<