Fabio
Fabio

Reputation: 2094

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.

Upvotes: 2

Views: 3535

Answers (2)

Fabio
Fabio

Reputation: 2094

Thanks to Moses Koledoye for spotting the problem. I was thinking I made a mistake in the Python code, but actually the problem was the characters of the filename.

According to MSDN the following are reserved characters that cannot be used in a filename on Windows:

< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78556

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.

Upvotes: 3

Related Questions