Converting date/time in YYYYMMDD/HHMMSS format to Python datetime
I have a date in YYYYMMDD format and a time in HHMMSS format as strings in 开发者_JS百科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?
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
.
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
You could clean up your existing code a bit with a generator (equivalent to a map):
generatedtime = datetime.datetime( *(int(x) for x in
(data[4][:4], data[4][4:6], data[4][6:], data[5][:2], data[5][2:4],data[5][4:6])
) )
or even, if you're crazy like a fox, you could make the datetime statement even cleaner (at the expense of adding a ridiculous line):
slices = ( (4, slice(4)), (4, slice(4,6) ), (4, slice(6,None)), (5, slice(2) ), (5, slice(2,4) ), (5, slice(4,6)) )
generatedtime = datetime.datetime( *(int(data[i][s]) for (i,s) in slices) )
精彩评论