Writing Date & Time to files?

Peter F. Ferris python at pferris.com
Thu May 9 12:39:21 EDT 2002


Greetings All,

This is my first posting to the group, though there will likely be many
more!  At the moment my only Python resource is the O'Reilly "Learning
Python".  Can't afford the $50 or so for "Programming Python"! I've started
in on my first script. But I digress...

I'm trying to build (concatenate) a string to write (append) to a file.  The
current relevant code looks something like:

NOTE: "targ_ipaddr" is an IP address -- currently 'hard coded' in the
script - for testing purposes, but eventually to be read from a list of IP's
in a file

.
.
.
import getpass
import sys
import telnetlib
from mx.DateTime import *

# Ping routine
tn.write("ping " + targ_ipaddr + "\n")

# Deal with the results of the ping.  Write to file and move on...
print "The results were: ", tn.read_some()
availresfile = open('/temp/availresfile.txt', 'a')
filestrng = targ_ipaddr + " was alive and well at: " + "\n"
availresfile.write(filestrng)
availresfile.close()

# Happy Trails!
print "The script lived to a ripe old age before expiring!"

.
.
.

NOTE: targ_ipaddr is an IP address -- currently 'hard coded' in the script -
for testing purposes, but eventually to be read from a list of IP's in a
file.

So far, so good...  My problem is, I would like to append a "date/time
stamp" to the text being written to the file. As you can see, I'm using the
mx.DateTime types.  They seem pretty good for my purposes.  The "now()" type
looks to be exactly what I want.  Does Python have any "built in" date /
time functionality?  I must be missing it in the book, if so.

Sooo, how can I add the time/date stamp to the "filestrng" string?  If I add
"+ now()" I get a "TypeError: cannot concatenate 'str' and 'DateTime'
objects" error.  Which is nice, but not very informative to me!  Can someone
help?! I throw myself (and my Python ignorance) on the "mercy of the court"!

Again, very simply (easy for ME to say! ;-)), I want to write something
similar to:

"xxx.xxx.xxx.xxxx was alive and well at: 2002-05-09 11:29:12.03" to the file
shown above.

All hints & tips are GREATLY appreciated!


Cordially,

--Peter








More information about the Python-list mailing list