Change CSV Name to CSV Date Time Python

Change CSV name to CSV date time python

I found the solution:

Only take the real time in a variable, and then concatenate with .csv (and also I put this csv output in a specific folder called output). Finally I open the csvFile with the variable name.

> now = datetime.now().strftime('%Y%m%d-%Hh%M')
> csvname = './output/' + now + '.csv'
> with open(csvname, 'w') as csvFile:

I can not do the second part of my problem. I want that if I run more than one time the code the date time name change or add (2), (3)... etc.

Using pandas to save to a csv file with date time appended to the filename

Your example works on Linux, but it doesn't work on Windows because of the restricted characters: < > : " / \ | ? *

Please replace : with something else.

How to format datetime values in csv file/column in python?

%H:%M:%S (capitals) are the format strings for time. re seems unneeded if you know the time column:

import csv
from datetime import datetime

with open('input.csv', "r", newline='') as inf, \
open('output.csv', "w", newline='') as outf:
reader = csv.reader(inf)
writer = csv.writer(outf)
writer.writerow(next(reader)) # copy header
for row in reader:
timestamp = datetime.strptime(row[2], '%d/%m/%Y %H:%M:%S.%f')
row[2] = timestamp.strftime('%Y-%m-%d %H:%M:%S')
writer.writerow(row)

Specify date in ouput file name using python

In the line:

month_year = (now.month, now.year),

you declared the variable month_year as a tuple and not string (as the exception says).

Change the line to this:
month_year = now.month

Changing the date format when writing out as a CSV

Have you tried doing line[26] = datetime.datetime.strptime(line[26], "%Y-%m-%d").strftime("%Y-%m-%d")

For example:

line = '2019-05-12'
print(type(line))

>>> <class 'str'>

line = datetime.datetime.strptime(line, "%Y-%m-%d").strftime("%Y-%m-%d")
print(line)

>>> 2019-12-05


Related Topics



Leave a reply



Submit