4

Input: A date field that includes date in various formats (including: yyyy/dd/mm, dd-mm-yyyy, etc.), for example:

2017/5/23
22-04-2015
20150504

Output: date field in a uniform format. All date values should be converted to the yyyymmdd format. i.e. above input should generate output as:

20170523
20150422
20150504

I tried using dateutils but the output format is 2015-05-23

from datetime import datetime
INPUT_FILENAME = 'date.txt'
OUTPUT_FILENAME = 'newfile.txt'
INPUT_DATE_FORMATS = {'column1dt': '%Y%m%d', 'column1dt': '%d/%m/%Y'}
OUTPUT_DATE_FORMAT = '%Y%m%d'
with open(INPUT_FILENAME, 'rt') as finput:
reader = finput.readlines()
with open(OUTPUT_FILENAME, 'wt') as foutput:
    print foutput 
    for row in reader: 
Zahra
  • 6,798
  • 9
  • 51
  • 76
reddy
  • 59
  • 1
  • 6

2 Answers2

8

Here is how you can guess the format of a date string:

import datetime

def guess_date(string):
    for fmt in ["%Y/%m/%d", "%d-%m-%Y", "%Y%m%d"]:
        try:
            return datetime.datetime.strptime(string, fmt).date()
        except ValueError:
            continue
    raise ValueError(string)

With the sample bellow:

samples = "2017/5/23", "22-04-2015", "20150504"

for sample in samples:
    print(guess_date(sample))

You get:

2017-05-23
2015-04-22
2015-05-04

Use d.strftime("%Y%m%d") to choose your desired format:

for sample in samples:
    d = guess_date(sample)
    print(d.strftime("%Y%m%d"))

You can also use dateutil.parser to parse a date in any format.

See example:

>>> from dateutil.parser import *
>>> now = parse("Sat Oct 11 17:13:46 UTC 2003")
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
  • Do you need more explanation? If not, I suggest you to upvote and [accept](https://meta.stackexchange.com/a/5235/344471) my answer. – Laurent LAPORTE Sep 04 '17 at 21:51
1

You can do something like that :

import datetime

datetime_object = datetime.datetime.strptime('22-04-2015', '%d-%m-%Y')
datetime_output = datetime_object.strftime('%Y%m%d')

Then you change the format of the date to suit your needs.

  • Thanks. This answer makes it simpler to understand the general gist of it. Together with https://strftime.org/ – Arete Sep 18 '22 at 11:54