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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With