How to split date and format it
Question:
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
Answers:
Well youd have to use 2 different python functions.
One is split
like so:
Dates = line.split('/')
And then use join
like so :
','.join(Dates)
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:)
Standard modules like
csv
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"))
output:
December, 21, 1995, Richard Alexander
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")
print(f"{name},{formatted_date}")
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"
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
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')
writer.writerow(data)
input.csv:
Richard Alexander,12/21/1995
John Smith,1/2/2002
Kilroy Washere,5/10/2010
output.csv:
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
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 f.read().splitlines():
print(line)
raw_date = line.split(',')[1]
date = format_to_format(raw_date, '%m/%d/%Y', '%m, %d, %Y')
print(date)
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
Well youd have to use 2 different python functions.
One is split
like so:
Dates = line.split('/')
And then use join
like so :
','.join(Dates)
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:)
Standard modules like
csv
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"))
output:
December, 21, 1995, Richard Alexander
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")
print(f"{name},{formatted_date}")
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"
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
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')
writer.writerow(data)
input.csv:
Richard Alexander,12/21/1995
John Smith,1/2/2002
Kilroy Washere,5/10/2010
output.csv:
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
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 f.read().splitlines():
print(line)
raw_date = line.split(',')[1]
date = format_to_format(raw_date, '%m/%d/%Y', '%m, %d, %Y')
print(date)