1

My goal is to write a script which will once I run it write the current Unix timestamp to a file. I tried several scripts which show the Unix timestamp directly such as this:

import time
print time.time()

While searching for an answer I came across a script which will write the current date and time with the datetime module to a file:

import datetime
f=open("/home/user/file.txt",'a')
f.write(datetime.datetime.now().ctime())

So I thought that if it's possible to write it with (datetime.datetime.now().ctime(), the same would be possible with for example:

import time
f=open("/home/user/file.txt",'a')
f.write(time.time())

Unfortunately I got this same error every time I tried something similar:TypeError: expected a string or other character buffer object. I've tried fixing this, but I couldn't so far. Any help or recommendation is greately appreciated.

Rin
  • 43
  • 8
  • 1
    Possible duplicate of [How to get file creation & modification date/times in Python?](https://stackoverflow.com/questions/237079/how-to-get-file-creation-modification-date-times-in-python) – Alex Nov 14 '18 at 14:02

2 Answers2

2

Try to convert your output to string, eg:

f.write(str(time.time()))

Jonathan R
  • 3,652
  • 3
  • 22
  • 40
2

Message is meaning: f.write requires a string typed data. time.time() returns a float that you have to cast into string.

import time
f=open("/home/ssh-jump/file.txt",'a')
f.write('%f' % time.time())
DylannCordel
  • 586
  • 5
  • 10