How can this datetime variable be converted to the string equivalent of this format in python?

I am using python 2.7.10

I have a datetime variable that contains 2015-03-31 21:02:36.452000

. I want to convert this datetime variable to a string that looks like 31-Mar-2015 21:02:36

.

How can I do this in python 2.7?

+3


source to share


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







All Articles