Richard
Richard

Reputation: 63

simple conversion between custom date/time formats in python (2.7)

I have looked far and wide to answer my question/solve my problem but I'm stuck.

I need to import a table of data, the first column of which, is composed of date/times like '20180214_145712'. Eventually I would like to export this data to a format that I think will work well with MS Excel i.e. '2018-02-14 14:57:12'.

Now I found a scrap of code that seems to do exaclty this:

import datetime
d = datetime.datetime(2018, 2, 14, 14, 57, 12)
'{:%Y-%m-%d %H:%M:%S}'.format(d)

Now when I input the first data/time value from my data file like so:

import datetime
d = datetime.datetime(int(data[0][0][0:4]), int(data[0][0][4:6]), int(data[0][0][6:8]), int(data[0][0][9:11]), int(data[0][0][11:13]), int(data[0][0][13:15])
'{:%Y-%m-%d %H:%M:%S}'.format(d)

I get an error in my Jupyter notebook:

File "<ipython-input-72-d0bef0623630>", line 4
'{:%Y-%m-%d %H:%M:%S}'.format(d)
                     ^
SyntaxError: invalid syntax

At this point I don't know how to proceed any further. The format identifiers seem to be fine, I think my input data is fine i.e. just integers. I checked on SO forum and found a useful post about the datetime module (other question on SO).

Any pointers would be useful.

Rich

Upvotes: 0

Views: 425

Answers (1)

Rakesh
Rakesh

Reputation: 82785

Try using the datetime module.

Ex:

import datetime
s = '20180214_145712'

print datetime.datetime.strptime(s, "%Y%m%d_%H%M%S").strftime("%Y-%m-%d %H:%M:%S")

Output:

2018-02-14 14:57:12

Upvotes: 1

Related Questions