0

I have a file with dates in a few different formats and am trying to get them all into YYYYMMDD format in Python. Most of the dates are in the below format:

Mon, 01 Jul 2013 16:33:59 GMT

and I have no idea how to get them into

20130701

I apologize if this is a pretty simple question---I am sort of new to python

EDIT: I am trying to do this for ANY given date. I used the 01 July as an example and in retrospect made it seem like I was asking a different question. So I guess I am looking for something that can both find dates and reformat them

user2479483
  • 11
  • 1
  • 4

2 Answers2

4

Use the python-dateutil library:

from dateutil import parser

dtobject = parser.parse(datestring)

The datutil.parser.parse() method recognises a wide variety of date formats, and returns a datetime.datetime() object.

Use the datetime.strftime() method if you want to format the result as a (uniform) string again:

dtobject.strftime('%Y%m%d')

Demo:

>>> from dateutil import parser
>>> parser.parse('Mon, 01 Jul 2013 16:33:59 GMT')
datetime.datetime(2013, 7, 1, 16, 33, 59, tzinfo=tzlocal())
>>> parser.parse('Mon, 01 Jul 2013 16:33:59 GMT').strftime('%Y%m%d')
'20130701'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Is it possible to do this for any given date (rather than selecting a specific date)? – user2479483 Jul 03 '13 at 20:29
  • @user2479483: I am not certain I follow you; I demonstrated how it all works with a specific date (the one you gave us in your post) but it'll work with most date formats you throw at it. Just pass it a string variable. – Martijn Pieters Jul 03 '13 at 20:49
  • Ok, let me clarify. The file I have has hundreds of dates so it would be tedious to do the entire thing using that method. Is there anyway to find all dates and change all of the date formats in a more elegant way than just going through each date individually? – user2479483 Jul 03 '13 at 22:04
  • See [Extracting date from a string in Python](http://stackoverflow.com/q/3276180) – Martijn Pieters Jul 03 '13 at 22:23
0

This can be achieved following way also:

import datetime
x = 'Mon, 01 Jul 2013 16:33:59 GMT'
''.join(str(datetime.datetime.strptime(x, '%a, %d %b %Y  %H:%M:%S %Z').date()).split('-'))

if any other parameter is introduced in your date string, you can include the directive . for example %p is Locale’s equivalent of either AM or PM.

Avichal Badaya
  • 3,423
  • 1
  • 21
  • 23