adding current date to a file name in a python script

M

markryde

Hello,

I am trying to add the current date to a file name in python script
like thus:

import os
import sys
import rpm
import time
import datetime

today = datetime.date.today()
print "The date is", today
myFile = '/work/output1'
myFile = myFile.join(today)
myFile = myFile.join(".txt")

print "myFile is",myFile


running the scripts indeed prints the correct date ,
but afterwards there is the following error:


The date is 2006-01-29
Traceback (most recent call last):
File "addDate.py", line 13, in ?
myFile = myFile.join(today)
TypeError: sequence expected, datetime.date found

How should I do this ?

Regards,
MR
 
S

Sybren Stuvel

(e-mail address removed) enlightened us with:
myFile = '/work/output1'
myFile = myFile.join(today)
myFile = myFile.join(".txt")

join does something completely different. You want:

myFile = '/work/output1/%s.txt' % today

Sybren
 
F

Fredrik Lundh

I am trying to add the current date to a file name in python script
like thus:

import os
import sys
import rpm
import time
import datetime

today = datetime.date.today()
print "The date is", today
myFile = '/work/output1'
myFile = myFile.join(today)
myFile = myFile.join(".txt")

print "myFile is",myFile


running the scripts indeed prints the correct date ,
but afterwards there is the following error:

The date is 2006-01-29
Traceback (most recent call last):
File "addDate.py", line 13, in ?
myFile = myFile.join(today)
TypeError: sequence expected, datetime.date found

How should I do this ?

datetime.date.today() returns a date object, not a string.

if the default string conversion is what you want, use str(today) to
convert to a string.

also note that "join" doesn't do what you think it does; "x.join(y)"
joins all members of the sequence y (which must all be strings) using
x as the separator. this gives you a filename like

'.2/work/output10/work/output10/work/output16/work/output1-/work/output10/work/o
utput11/work/output1-/work/output12/work/output19t2/work/output10/work/output10/
work/output16/work/output1-/work/output10/work/output11/work/output1-/work/outpu
t12/work/output19x2/work/output10/work/output10/work/output16/work/output1-/work
/output10/work/output11/work/output1-/work/output12/work/output19t'

which is probably not what you want.

to fix this, you can use +=

myFile = '/work/output1'
myFile += str(today)
myFile += ".txt"

or % formatting:

myFile = '/work/output1%s.txt' % today

(here, "%s" does the str() call for you).

</F>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top