Fabio Fabio - 1 year ago 89
Python Question

formatting date, time and string for filename

I want to create a csv file with a filename of the following format:

"day-month-year hour:minute-malware_scan.csv"

Example:" 6-8-2016 21:45-malware_scan.csv"

The first part of the filename is formed by the actual date and time at file creation time, instead "-malware_scan.csv" is a fixed string.

I know that in order to get the date and time I should use the time or datetime module and the strftime() function for formatting.

At first I tried with:

t = datetime.datetime.now()
formatted_time = t.strftime(%d-%m-%y %H:%M)
filename = formatted_time + "-malware_scan.csv"
with open(filename, "a") as f:

I didn't get the expected result, so I tried another way:

i = datetime.datetime.now()
file_to_open = "{day}-{month}-{year} {hour}:{minute}-malware_scan.csv".format(day = i.day, month = i.month, year = i.year, hour = i.hour, minute = i.minute)
with open(file_to_open, "a") as f:

Also using the code above I don't get the expected result.
I get a filename of this kind: "6-8-2016 21". Day, month, year and hour is displayed but the minutes and the rest of the string (-malware_scan.csv) isn't diplayed.

I'm focusing only on the filename with this question, not on the csv writing itself, whose code is omitted.

Answer Source

The : character is not allowed for filenames on PC. You could discard the : separator entirely:

>>> from datetime import datetime
>>> t = datetime.now()
>>> formatted_time = t.strftime('%d-%m-%y %H%M')
>>> formatted_time
'06-08-16 2226'
>>> datetime.strptime(formatted_time, '%d-%m-%y %H%M')
datetime.datetime(2016, 8, 6, 22, 26)

Or replace that character with an underscore or hyphen.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download