26

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?

1
  • 1
    Your code, while awkward looking, does the job nicely. Commented Mar 4, 2010 at 14:39

3 Answers 3

60

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If the timestamp is not specified, the time will be treated as local time. The following example converts a UTC time to Unix timestamp: datetime.datetime.strptime(timeval, "%Y%m%d%H%M%S").replace(tzinfo=datetime.timezone.utc).timestamp() (I actually use this for parsing a FTP MDTM response)
8

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

Comments

0

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) ) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.