User Tools

Site Tools


write_current_date_and_time_to_file_and_screen

This is an old revision of the document!


Write Current Date and Time to File and Screen



This Python 3 example will write the current date and time to a file. Useful information for any projects that require file writes or the use of date time.

You can download the Python file here:

  #!/usr/bin/python
  #
  # Python 3 Script
  #
  # Alan Walker
  # Aug 2016
  #
  #
  # Write current date and time to file and screen
  # Created to see how long Rpi would run from batteries
  # by comparing first and last date time in file
  #
  #
  
      
  from datetime import datetime    # Import Libraries
  import time
  
  var=1                      
  while var == 1:    # creates a never ending loop
      text = "{:%B %d %Y %H:%M:%S\n}".format(datetime.now())  # make the variable text = the current 
                                                              # date and     time.
      saveFile = open('blt.txt','a')                          # open file for append
      
      saveFile.write(text)                                    # write date and time (and a new line) to file
      saveFile.close()                                        # close the file
     
      print (text)                                            # print date and time (held in var called text)
                                                              # to screen
      time.sleep(30)                                          # sleep for x seconds



write_current_date_and_time_to_file_and_screen.1470948928.txt.gz · Last modified: 2023/03/09 22:35 (external edit)