How can this datetime variable be converted to the string equivalent of this format in python?
1 answer
Use strptime to create a datetime object, then use strftime to format it the way you want:
from datetime import datetime
s= "2015-05-31 21:02:36.452000"
print(datetime.strptime(s,"%Y-%m-%d %H:%M:%S.%f").strftime("%d-%b-%Y %H:%m:%S"))
31-May-2015 21:05:36
The format string is as follows:
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%f Microsecond as a decimal number
In strftime we use% b which:
%b Localeβs abbreviated month name.
Obviously we are just ignoring the microseconds in the output line.
If you already have a datetime object, just call strftime on the datetime object:
print(dt.strftime("%d-%b-%Y %H:%m:%S"))
+7
source to share