Converting date between formats in Python

November 27th, 2016 by Alex Leave a reply »

Python is very versatile when it comes to processing data. Dates are of no exclusion, here’s a simple example.

Let’s say we have a date in a human-friendly format like

time_created="Tue, 14 Jun 2016 10:35:05 GMT"

While this is a nicely formatted date, it is a no-go if we need to insert it into a database of some sort (for example, MySQL). Let’s convert it

import datetime
datetime_parsed = datetime.datetime.strptime(time_created, "%a, %d %b %Y %H:%M:%S GMT")
time_created_db = datetime_parsed.strftime('%Y-%m-%d %H:%M:%S')    ### 2016-06-14 10:35:05

What we did here is used the datetime class method strptime, and provided it the format of our datetime string. The full list of available formats is available in python docs

That was easy.

Comments are closed.