0

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

Richard
  • 63
  • 5
  • Have a look at datetime functions strftime and strptime. Use strptime to get a date object from a string and strftime to parse a datetime object to a string in desired format. – Igl3 Feb 26 '18 at 12:19

1 Answers1

1

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
Rakesh
  • 81,458
  • 17
  • 76
  • 113