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
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)
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: {name}\nDate: {formatted_date}")
Name: Richard Alexander
Date: December 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:)
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
I am running some code and I would like to save a csv file which include the current date and time in its name.
For example: I run some code now (12:24, Jan 15) and I would like to have something like
name_1224_01152021.csv
Can you tell me how to print/save this information, please?
The following code should format the name as per your requirement:
import datetime
name = f'name_{datetime.datetime.now().strftime("%H%M_%m%d%Y")}.csv'
print(name)
# prints 'name_0628_01152021.csv'
Here is the code according to your question :
from datetime import datetime
filename = datetime.now().strftime('filename_%H%M_%m%d%Y.csv')
with open(filename, "w+") as f_output:
csv_output = csv.writer(f_output)
csv_output.writerow(["row1", "row2"])
in filename you have to write your file name the output of this will be shown as
filename_0620_01152021_.csv
Something like this might be what you want :
from datetime import date
today = date.today()
# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
fname = "name_1224" + d1 + ".csv"
#fname = "name_1224" + str(d1) + ".csv"
import datetime
val_time =datetime.time.now()
now you can append name and val_time and save file with that name
You can format your date with strftime.
import datetime
filename = datetime.datetime.now().strftime('name_%H%_%d%m%Y.csv')
then you can do something like
open(filename, "w").write("blahblah")
Very new to python and programming in general. I am trying to create a script that takes a start time and end time from a csv, computes the duration in minutes and than writes the value into a new csv.
with open('testdata1.csv','r') as csv_file:
csv_reader = csv.DictReader(csv_file)
with open('new_testdata1.csv','w') as new_file:
fieldnames = ['Title', 'Description', 'Location', 'Start', 'End',
'Date', 'Duration_minutes']
csv_writer = csv.DictWriter(new_file, fieldnames = fieldnames)
csv_writer.writeheader()
for line in csv_reader:
start = line['Start']
end = line['End']
date = convertdate(end)
end = converttime(end)
start = converttime(start)
duration = end - start
print(duration)
How do I get the duration variable written into Duration field?
Much thanks
Full script for reference if necessary
total.py
# fully functioning script, need to convert into function still
import datetime
import csv
def converttime(string):
#convert string to standard format
FullDate = datetime.datetime.strptime(string, "%B %d, %Y at %I:%M%p")
#convert variable to string
FullDate = str(FullDate)
#slice out time
time = FullDate[11:16]
#convert time to minutes
hr = int(time[0:2])
mins = int(time[3:5])
minutes = hr * 60 + mins
return minutes
def convertdate(string):
#convert string to standard format
FullDate = datetime.datetime.strptime(string, "%B %d, %Y at %I:%M%p")
#convert variable to string
FullDate = str(FullDate)
#slice out date
date = FullDate[0:10]
return date
def main():
#get string
with open('testdata1.csv','r') as csv_file:
csv_reader = csv.DictReader(csv_file)
with open('new_testdata1.csv','w') as new_file:
fieldnames = ['Title', 'Description', 'Location', 'Start', 'End',
'Date', 'Duration_minutes']
csv_writer = csv.DictWriter(new_file, fieldnames = fieldnames)
csv_writer.writeheader()
for line in csv_reader:
start = line['Start']
end = line['End']
date = convertdate(end)
end = converttime(end)
start = converttime(start)
duration = end - start
print(duration)
main()
here your duration_time is your duration for each row
from csv import writer
from csv import reader
duration_time = 'Some Text'
# Open the input_file in read mode and output_file in write mode
with open('input.csv', 'r') as read_obj, \
open('output_1.csv', 'w', newline='') as write_obj:
# Create a csv.reader object from the input file object
csv_reader = reader(read_obj)
# Create a csv.writer object from the output file object
csv_writer = writer(write_obj)
# Read each row of the input csv file as list
for row in csv_reader:
# Append the duration in the row / list
row.append(duration_time)
# Add the updated row / list to the output file
csv_writer.writerow(row)
this will add duration_time to each row
I am trying to get python to automatically add the current time and date as a filename after it finishes with running the report its designed to.
Get current date from datetime module using datetime.date.today(), use strftime() to parse it to your required format and add it to your filename string.
import datetime
filename = 'XYZ Report {0}.txt'
current_date = datetime.date.today().strftime('%d %b %Y')
filename = filename.format(current_date)
# filename = XYZ Report 19 Sep 2018.txt
with open(filename) as file_obj:
# File writing logic
Answer is:
import time
import xlwt
import csv
date_string = time.strftime("%Y%m%d %H.%M")
if saving to CSV document
data_output = []
with open('C:\\Users\\Desktop\\File Name' + date_string + '.csv', 'a+') as f:
w = csv.writer(f, delimiter=',')
for data in data_output:
w.writerow(data)
f.close()
if saving to Excel document
df.to_excel('C:\\Users\\Desktop\\File Name' + date_string + '.xlsx')
if saving to Txt document
df.to_csv('C:\\Users\\Desktop\\File Name' + date_string + '.txt')
I have a column filled with dates. I imported all of the data using the csv importer. (parse.com)
I have tried reformatting the dates to match the formatting used in parse's other datetime fields. Here's the python I used to reformat the initial dates. It runs in a folder which contains my monthly logs as csv files. The date for changing is in the fifth column (ie - row[4]).
import os
import csv
import datetime
import time
from os import listdir
mypath = os.getcwd()
def find_csv_filenames( path_to_dir, suffix=".csv" ):
filenames = listdir(path_to_dir)
return [ filename for filename in filenames if filename.endswith( suffix ) ]
for each in find_csv_filenames(mypath):
with open(each,'rb') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
next(spamreader, None) # skip the headers
for row in spamreader:
# twilio formatting "yyyy-MM-dd hh:mm:ss PDT" / or sometimes PST
date_object = datetime.datetime.strptime(row[4][:-4], "%Y-%m-%d %H:%M:%S")
# parse formatting"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"
row[4] = date_object.strftime("%Y-%m-%dT%H:%M:%S.1%MZ")
row[2] = ''
print ', '.join(row)