Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert different formats of date into one format using python [duplicate]

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: 
like image 212
reddy Avatar asked Mar 09 '23 01:03

reddy


2 Answers

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")
like image 71
Laurent LAPORTE Avatar answered Apr 26 '23 09:04

Laurent LAPORTE


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.

like image 40
V. Marceddu Avatar answered Apr 26 '23 10:04

V. Marceddu