How to split date and format it


I already figured out how to split the name from the date from a imported text file. I am trying to figure out how I could change the date from a mm/dd/yyyy format into month, date, yyyy.

This is the code I have to separate the names from the date:
with open("dates.txt",'r') as data_file: for line in data_file: data = line.split(',')
would I have to do an import such as datetime or pandas?

and here is how the first line of the text file looks like:
Richard Alexander,12/21/1995

Asked By: Slope10



Well youd have to use 2 different python functions.
One is split like so:

Dates = line.split('/') 

And then use join like so :


Of course youll need to iterate over it in a four loop beacuse you get a lot of 3 close elements as a single date, or even better after splitting each line join it to a different variable,
Hope it helped:)

Answered By: Mark Kapilyan

Standard modules like
and datetime
are your friend!

from io import StringIO
import csv
import datetime as dt

def parse(fin):
    fmt = "%B, %d, %Y,"  # Month, date, yyyy
    sheet = csv.reader(fin)
    for name, date in sheet:
        date = dt.datetime.strptime(date, "%m/%d/%Y")
        print(date.strftime(fmt), name)

if __name__ == "__main__":
    parse(StringIO("Richard Alexander,12/21/1995"))


December, 21, 1995, Richard Alexander
Answered By: J_H

Here is a possible solution:

from datetime import datetime 

name_and_date = "Richard Alexander,12/21/1995"
name, date_str = name_and_date.split(",")

date = datetime.strptime(date_str, "%m/%d/%Y")
formatted_date = date.strftime("%B %d, %Y")


Richard Alexander,December 21, 1995

But when written to csv, the date will be automatically wrapped in quotes like so:
Richard Alexander,"December 21, 1995"

Answered By: Jamiu S.

You could try this:

import calendar

with open("dates.txt",'r') as data_file:
    for line in data_file:
        data = line.split(',')
        date = data[1].split('/')
        data[1] = f"{calendar.month_name[int(date[0])]}, {date[1]}, {date[2]}"
        # write data to a new file here
Answered By: Aleksa Majkic

Using standard libraries to parse and reformat the time and handle a CSV correctly:

import csv
import datetime as dt

# Never use the default encoding.  It's OS-specific.
# newline='' is a documented requirement for csv.reader/writer.
with (open('input.csv', 'r', encoding='utf8', newline='') as fin,
      open('output.csv', 'w', encoding='utf8', newline='') as fout):
    reader = csv.reader(fin)
    writer = csv.writer(fout)
    for data in reader:
        d = dt.datetime.strptime(data[1], '%m/%d/%Y')
        data[1] = d.strftime('%B %d, %Y')


Richard Alexander,12/21/1995
John Smith,1/2/2002
Kilroy Washere,5/10/2010


Richard Alexander,"December 21, 1995"
John Smith,"January 02, 2002"
Kilroy Washere,"May 10, 2010"

Using pandas:

import pandas as pd

df = pd.read_csv('input.csv', encoding='utf8', header=None, parse_dates=[1])
df.to_csv('output.csv', encoding='utf8', index=False, header=None, date_format='%B %d, %Y')

(same output)

See Also: Format Codes

Answered By: Mark Tolonen
import datetime

def format_to_format(raw_date: str, source_format: str, target_format: str) -> str:
    :raw_date: source date string
    :source_format: source date string format e.g '%m/%d/%Y'
    :target_format: e.g '%m-%d-%Y'

    :return: formatted date string
    date_obj = datetime.datetime.strptime(raw_date, source_format)
    result = date_obj.strftime(target_format)
    return result

if __name__ == "__main__":
    with open("dates.txt", 'r') as f:
        for line in
            raw_date = line.split(',')[1]
            date = format_to_format(raw_date, '%m/%d/%Y', '%m, %d, %Y')

Answered By: Evgene
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.