User Tools

Site Tools


write_current_date_and_time_to_file_and_screen

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:

<sxh [py][; options for SyntaxHighlighter]>

  #!/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

</sxh>

Example Output

August 11 2016 21:40:12
August 11 2016 21:40:42
August 11 2016 21:41:12
August 11 2016 21:41:42
August 11 2016 21:42:13
August 11 2016 21:42:43
August 11 2016 21:43:13
August 11 2016 21:43:43
August 11 2016 21:44:13
August 11 2016 21:44:43
August 11 2016 21:45:13
August 11 2016 21:45:43
August 11 2016 21:46:13
August 11 2016 21:46:43
August 11 2016 21:47:13
August 11 2016 21:47:43
August 11 2016 21:48:13
August 11 2016 21:48:43
August 11 2016 21:49:13
August 11 2016 21:49:43
August 11 2016 21:50:13
August 11 2016 21:50:43
August 11 2016 21:51:13
August 11 2016 21:51:43
August 11 2016 21:52:13
August 11 2016 21:52:43
August 11 2016 21:53:13
August 11 2016 21:53:43
August 11 2016 21:54:13
August 11 2016 21:54:43
August 11 2016 21:55:13
August 11 2016 21:55:43
August 11 2016 21:56:13
August 11 2016 21:56:43
August 11 2016 21:57:13


write_current_date_and_time_to_file_and_screen.txt · Last modified: 2023/03/09 22:35 by 127.0.0.1