Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting date/time in YYYYMMDD/HHMMSS format to Python datetime

Tags:

I have a date in YYYYMMDD format and a time in HHMMSS format as strings in the 4th and 5th elements in a list. I.E.:

data[4] = '20100304' data[5] = '082835' 

I am creating an instance of datetime (in a field named generates) like this:

generatedtime = datetime.datetime(int(data[4][:4]),int(data[4][4:6]),int(data[4][6:]),int(data[5][:2]),int(data[5][2:4]),int(data[5][4:6])) 

Given that the input format cannot change, is there a cleaner way I should be creating my instance of the datetime object?

like image 260
Wes Avatar asked Mar 04 '10 14:03

Wes


2 Answers

No need to import time; datetime.datetime.strptime can do it by itself.

import datetime dt=datetime.datetime.strptime(data[4]+data[5],'%Y%m%d%H%M%S') print(dt) # 2010-03-04 08:28:35 

For information on the format codes (e.g. %Y%m%d%H%M%S) available, see the docs for strftime.

like image 156
unutbu Avatar answered Sep 18 '22 21:09

unutbu


You might take a look at time.strptime.

import time time.strptime('20100304 082835', '%Y%m%d %H%M%S') 

The above assumes a 24-hour clock (%H). Use %I instead if using a 12-hour clock.

For a complete list of available format directives, check out the docs for time.strftime

like image 28
Mark Biek Avatar answered Sep 20 '22 21:09

Mark Biek