简体   繁体   中英

Convert any Date String Format to a specific date format string

I am making a generic tool which can take up any csv file.I have a csv file which looks something like this. The first row is the column name and the second row is the type of variable. sam.csv

Time,M1,M2,M3,CityName
temp,num,num,num,city
20-06-13,19,20,0,aligarh
20-02-13,25,42,7,agra
20-03-13,23,35,4,aligarh
20-03-13,21,32,3,allahabad
20-03-13,17,27,1,aligarh
20-02-13,16,40,5,aligarh

Other CSV file looks like:

Time,M1,M2,M3,CityName
temp,num,num,num,city
20/8/16,789,300,10,new york
12/6/17,464,67,23,delhi
12/6/17,904,98,78,delhi

So, there could be any date format or it could be a time stamp.I want to convert it to "20-May-13" or "%d-%b-%y" format string everytime and sort the column from oldest date to the newest date. I have been able to search the column name where the type is "temp" and try to convert it to the required format but all the methods require me to specify the original format which is not possible in my case. Code-- import csv import time from datetime import datetime,date import pandas as pd import dateutil from dateutil.parser import parse

filename = 'sam.csv'
data_date = pd.read_csv(filename)
column_name = data_date.ix[:, data_date.loc[0] == "temp"]
column_work = column_name.iloc[1:]
column_some = column_work.iloc[:,0]
default_date = datetime.combine(date.today(), datetime.min.time()).replace(day=1)
for line in column_some:
        print(parse(line[0], default=default_date).strftime("%d-%b-%y"))

In "sam.csv", the dates are in 2013. But in my output it gives the correct format but all the 6 dates as 2-Mar-2018

You can use the dateutil library for converting any date format to your required format.

Ex:

import csv
from dateutil.parser import parse
p = "PATH_TO_YOUR_CSV.csv"      #I have used your sample data to test. 

with open(p, "r") as infile:
    reader = csv.reader(infile)
    next(reader)     #Skip Header
    next(reader)     #Skip Header
    for line in reader:
        print(parse(line[0]).strftime("%d-%B-%y"))    #Parse Date and convert it to date-month-year

Output:

20-June-13
20-February-13
20-March-13
20-March-13
20-March-13
20-February-13
20-August-16
06-December-17
06-December-17

MoreInfo on Dateutil

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM