As the title says, how can I save a file (in this case a previously selected photo) into a specific directory and also name the saved file (I want to name it with today's date - eg: 01-01-2016.jpg)?
Here's some of my code:
import os.path
import datetime
todays_date = datetime.date.today ()
def add_pic (pic):
if not os.path.exists ("Pictures"):
os.makedirs ("Pictures")
photo_name = todays_date + ".jpg"
pic.save ("Pictures/"photo_name)
I get this error:
TypeError: unsupported operand type(s) for +: 'datetime.date' and 'str'
for this line:
photo_name = todays_date + ".jpg"
Plus, I'm not sure about the last line either, so pls help!
Use .strftime()
to "convert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.":
photo_name = todays_date.strftime('%m-%d-%Y') + ".jpg"
pic.save(os.path.join("Pictures",photo_name))
Also use os.path.join()
for a cross-platform method of joining directory to filename.
As @Blckknght says in a comment: please note that '%m-%d-%Y'
is something for which you can change order, eg '%Y-%m-%d'
is a common variant.
是的,上面的解决方案应该可行,误解你正在做的就是用字符串添加时间值。
This won't work because datetime.date.today()
returns a date object. Try converting to string by calling the .__str__()
method, the .ctime()
method, or the .strftime()
method.
See https://docs.python.org/2/library/datetime.html#date-objects .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.