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: 
2
  • also you can convert date into ordinal date and convert it back to any desire format Commented May 23, 2017 at 11:49
  • @reddy, What is your input? Is it of type string? Commented May 23, 2017 at 11:51

2 Answers 2

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Do you need more explanation? If not, I suggest you to upvote and accept my answer.
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.

1 Comment

Thanks. This answer makes it simpler to understand the general gist of it. Together with strftime.org 💖

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.