Wednesday, July 16, 2014

How to convert a datetime stamp in YYYYMMDD HH:MM:SS format to a datetime object

Code
from datetime import datetime                                              #1
datetimestring = '20140714 04:05:10'                                       #2
datetimeobject = datetime.strptime(datetimestring,'%Y%m%d %H:%M:%S')       #3
print datetimeobject                                                       #4
 


How this works - Line by Line

from datetime import datetime                                              #1
 
Imports the datetime class from the datetime module, which is standard


datetimestring = '20140714 04:05:10'                                       #2

Creating an example date time string in the YYYYMMDD HH:MM:SS format.

datetimeobject = datetime.strptime(datetimestring,'%Y%m%d %H:%M:%S')       #3

Converts the datetimestring into a datetimeobject using the datetime class's strptime method.


print datetimeobject                                                       #4
 
Prints the datetimeobject. This datetimeobject can then be reconverted into another format using the strftime method. i.e. datetimeobject.strftime('%m%d%Y %H%M%S')

No comments:

Post a Comment