Home > Back-end >  Getting error OSError: [Errno 22] Invalid argument: 'alarms_2022-02-01 18:39:58.173215.json
Getting error OSError: [Errno 22] Invalid argument: 'alarms_2022-02-01 18:39:58.173215.json

Time:02-01

Could you please help me on solving below error.

I wanted the file name to have the date and time in it while its getting saved. The file is saving "data" value.

I used this its working. But i wanted date and time as well.

file_name = f"alarms_{int(time.time())}.json"
with open(file_name,"ab") as file:
    file.write(data)

enter image description here

CodePudding user response:

Your resulting filename alarms_2022-02-01 18:39:58.173215.json is not a valid Windows filename (it contains : colons).

Try formatting the datetime to something more sensible, like this:

...
file_name = datetime.datetime.now().strftime("alarm_%Y%m%d-%H%M%S.%f.json")
...

CodePudding user response:

Step 1: Turn datetime to string before writing to file name. Make a new variable called date_string. This method keeps the date and time information.

from datetime import datetime

date_string = f'{datetime.datetime.now():%Y-%m-%d %H:%M:%S%z}'

Step 2: Also make sure there is no space by replacing space with underscore_.

date_string = date_string.replace(" ", "_")

Step 3:

file_name = f"alarms_{date_string}.json"
with open(file_name,"ab") as file:
    file.write(data)
  •  Tags:  
  • Related