Python: Converting a date string to timestamp
I’ve been playing around with Python over the last few days while cleaning up a data set and one thing I wanted to do was translate date strings into a timestamp.
I started with a date in this format:
date_text = "13SEP2014"
So the first step is to translate that into a Python date - the strftime section of the documentation is useful for figuring out which format code is needed:
import datetime
date_text = "13SEP2014"
date = datetime.datetime.strptime(date_text, "%d%b%Y")
print(date)
$ python dates.py
2014-09-13 00:00:00
The next step was to translate that to a UNIX timestamp. I thought there might be a method or property on the Date object that I could access but I couldn’t find one and so ended up using calendar to do the transformation:
import datetime
import calendar
date_text = "13SEP2014"
date = datetime.datetime.strptime(date_text, "%d%b%Y")
print(date)
print(calendar.timegm(date.utctimetuple()))
$ python dates.py
2014-09-13 00:00:00
1410566400
It’s not too tricky so hopefully I shall remember next time.
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.