Scroll to top

Python date to string

In Python you can use the datetime module to work with dates and temporal data. A typical way to use it as such:

>>> import datetime
>>> datetime.datetime(2015, 1, 1, 0, 0)
datetime.datetime(2015, 1, 1, 0, 0)

In this example we create a date time object with the date of 1.1.2015 at 00:00/12:00AM. If you have a date string at hand and don’t want to parse the arguments for the datetime constructor yourself, no problem, there is a function that can parse the date string for you:

>>> datetime.datetime.strptime('Jan 1 2015  12:00AM', '%b %d %Y %I:%M%p')
datetime.datetime(2015, 1, 1, 0, 0)

This method has two arguments: the date string and the date format string. The date string contains the date that you would like to convert to a datetime object, which can be any valid date representation; and the date format string contains the date format of your date string, so that the conversion function can understand how to parse the string date.

The date format string from the example tells the conversion function that in the date string there will first be a month (%b), then a day (%d), then a year (%Y) and finally a time in AM/PM format (%I:%M%p). By using a date format string a variety of different date strings can be properly parsed.

Now, if we already have some datetime objects, we may want to turn those into a more human-readable format. This is also easily done using the datetime functionality:

>>> datetime.datetime(2015, 1, 1, 0, 0).strftime('%b %d %Y %I:%M%p')
'Jan 01 2015 12:00AM'

Here we simply take our datetime object and call a datetime to string conversion function on it with an appropriate date format string. In this example we use the same date format string as before to generate a human-readable string representation of our already familiar date. Here the date string format tells the function how the date string should be formatted.

Author avatar

Post a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.