NeoVe
NeoVe

Reputation: 3897

Change string format column date into dd/mm/yyyy

I have a column which contains data on this format (a string, essentially):

21 apr 2015

I need to parse this column, which contains several items, and output to date format, like:

dd/mm/yyyy

In python, I have seen many examples, but it always deals with a "sort of" formatted date, these are really not formatted, as You can see, so how could achieve that?

I can't use pandas though.

I have seen examples like this:

string_date = "2013-09-28 20:30:55.78200"
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")

But, this deals with a string, which has "some" format.

Any ideas about this?

Upvotes: 1

Views: 257

Answers (2)

oppressionslayer
oppressionslayer

Reputation: 7204

You can create a function that returns the correct format you need using strptime and strftime for formatting

from datetime import datetime

def convert_csv_date(csv_date):
  return datetime.strptime(csv_date, "%d %b %Y").strftime("%d/%m/%Y")

csv_date="21 apr 2015"
In [492]: convert_csv_date(csv_date)                                                                                                                          
Out[492]: '21/04/2015'

UPDATE: Here is a full program that writes data to a csv file in the format of your dates, then uses convert_csv_date to update the data and write a new file to compare with. I hope this helps ( you may have to change the file directory name, i used /tmp):

import csv
from datetime import datetime

def convert_csv_date(csv_date):
  return datetime.strptime(csv_date, "%d %b %Y").strftime("%d/%m/%Y")


lines = [['Vacation_Days', 'Date'],
 ['New Years', '01 jan 2019'],
 ['Labor Day', '02 sep 2019'],
 ['Thanksgiving', '24 nov 2019']]

with open('/tmp/output.csv', 'w') as writer:
    fd = csv.writer(writer)
    fd.writerows(lines)

r = csv.reader(open('/tmp/output.csv')) # Here's a sample date csv file
lines = list(r)

for item in lines[1:]: 
   item[1] = convert_csv_date(str(item[1])) 

print(lines)

with open('/tmp/output_test.csv', 'w') as writer:
    fd = csv.writer(writer)
    fd.writerows(lines)

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521093

Using the datetime library, you may handle this in two steps. First, call strptime to convert your input text date 21 apr 2015 to a bona fide Python datetime. Then, to generate another date string in the format %d/%m/%Y, call strftime:

inp = "21 apr 2015"
out = datetime.strptime(inp, "%d %b %Y")
print(out.strftime("%d/%m/%Y"))

This prints:

21/04/2015

Upvotes: 1

Related Questions