How can this datetime variable be converted to the string equivalent of this format in python?
Question: I am using python 2.7.10

I have a datetime variable which contains `2015-03-31 21:02:36.452000`. I want
to convert this datetime variable into a string which looks like `31-Mar-2015
21:02:36`.

How can this be done in python 2.7?


Answer: Use strptime to create a datetime object then use strftime to format it they
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 the following:

    
    
    %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 is:

    
    
    %b  Locale’s abbreviated month name.
    

Obviously we just ignore the microseconds in the output string.

If you already have a datetime object just call strftime on the datetime
object:

    
    
    print(dt.strftime("%d-%b-%Y %H:%m:%S"))
    

