Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python PIL save file with datetime as name

I'm relatively new to python and know very little syntax, but I'm willing to learn as much as possible. Simply put I want to use the save feature in PIL to save a .png with the file's name being the current date and time. This may be complicated by the fact that I'm not using PIL directly, but through the Videocapture module, but i doubt it. this is my code that works

from VideoCapture import Device
cam = Device()
cam.saveSnapshot('C:\Users\Myname\Dropbox\Foldes\image.png', timestamp=3, boldfont=1, textpos='bc')

Its short, but it does what I need it to. I realize Datetime will need to be imported, But I can't get the data as the name without errors. yes i have tried the str() command. Any help will be greatly appreciated.

like image 359
robocop408 Avatar asked Jun 13 '11 07:06

robocop408


People also ask

How do you create a filename with a date and time in python?

First, import the module and then get the current time with datetime. now() object. Now convert it into a string and then create a file with the file object like a regular file is created using file handling concepts in python.

What is datetime datetime now () in Python?

Python datetime: datetime. now(tz=None) returns the current local date and time. If optional argument tz is None or not specified, this is like today().

Is datetime a data type in Python?

Python Datetime A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.


1 Answers

'C:\Users\Myname\Dropbox\Foldes\image.png'

In strings in Python, backslashes have special meaning so you need to treat them differently. You can either use two of them instead of one...

'C:\\Users\\Myname\\Dropbox\\Foldes\\image.png'

...or you can put an r before the string (as long as it doesn't end with a backslash)

r'C:\Users\Myname\Dropbox\Foldes\image.png'

To generate a string containing the current day in YYYY-MM-DD-HH:MM format, we can use the datetime module like this. To format the timestamp differently, consult the documentation here.

import datetime
date_string = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M")

As a shorter alternative, you could use the similar time module instead:

import time
date_string = time.strftime("%Y-%m-%d-%H:%M")

After this, you should just be able to do

cam.saveSnapshot(r'C:\Users\Myname\Dropbox\Foldes\image-' + date_string + '.png',
                 timestamp=3, boldfont=1, textpos='bc')

to save the image with the datetime in the filename. (I have split the function call over two lines for readability, see this question for some explanation of how this works.)

like image 158
Jeremy Avatar answered Nov 07 '22 12:11

Jeremy