-3

I want to write Datetime every second in while loop , but it writes one time twice because of the loop .

Note : I don't want to use time.sleep() cause it would make the whole while loop effected.

The Example of my problem in a text file :

register : user 1 at 13:30:34 

register : user 1 at 13:30:34
jimbob88
  • 697
  • 5
  • 20
ghostDs
  • 95
  • 2
  • 8

5 Answers5

1

Please try this and use file write accordingly

 import datetime

 start_time = datetime.datetime.now()
 print(start_time)
 while True:
    if (datetime.datetime.now() - start_time).seconds == 1:
       start_time = datetime.datetime.now()
       print(start_time)
Aman Raparia
  • 494
  • 1
  • 5
  • 13
0

Try this code !

You can use the gmtime to print the time & for every second delay you can use the sleep() function by importing time library.

from time import gmtime, strftime
import time

while True:
    print(strftime("%H:%M:%S", gmtime()))
    time.sleep(1)

Output :

11:10:23                                                                                                               
11:10:24                                                                                                               
11:10:25                                                                                                               
11:10:26                                                                                                               
11:10:27                                                                                                               
11:10:28                                                                                                               
11:10:29                                                                                                               
11:10:30 
Usman
  • 1,983
  • 15
  • 28
0

If I got the point, you want to append time each second while the rest of code is running.

To achieve that you better to make a thread. The Multi Threading lets you to run your code while you're using sleep() withing your code.

Mohammad Jafari
  • 1,742
  • 13
  • 17
  • yes , thats true i did it but the time write the time twice but now i figured it out.thanks anyway – ghostDs Dec 28 '18 at 12:39
0

There are many ways in which you could receive the desired effect, but to start off we need a function that we can call.

def save_datetime(file='date.txt', user=getpass.getuser()):
    with open(file, 'a+') as f:
        f.write('register: ' + user + '\t' + str(datetime.datetime.now().time()) + '\n')

We now need a function for the loop.

def threadingtime_every_sec(sec=60):
    import threading, time
    def loop():
        while True:
            save_datetime()
            time.sleep(sec)
    threading.Thread(target=loop).start()

I understand you don't want to use time.sleep() but because it runs a thread it isn't noticeable and so is run separately. The full script would be:

import datetime
import getpass
import threading
import time

def save_datetime(file='date.txt', user=getpass.getuser()):
    with open(file, 'a+') as f:
        f.write('register: ' + user + '\t' + str(datetime.datetime.now().time()) + '\n')

def threadingtime_every_sec(sec=60):
    def loop():
        while True:
            save_datetime()
            time.sleep(sec)
    threading.Thread(target=loop).start()

if __name__ == '__main__':
    threadingtime_every_sec(1)

I would thoroughly recommend this answer and this question as it gives you multiple ways - and a much better threading system using the Timer function and a Class. The full script in your case would be:

import threading
import time
import getpass
import datetime

class RepeatedTimer(object):
  def __init__(self, interval, function, *args, **kwargs):
    self._timer = None
    self.interval = interval
    self.function = function
    self.args = args
    self.kwargs = kwargs
    self.is_running = False
    self.next_call = time.time()
    self.start()

  def _run(self):
    self.is_running = False
    self.start()
    self.function(*self.args, **self.kwargs)

  def start(self):
    if not self.is_running:
      self.next_call += self.interval
      self._timer = threading.Timer(self.next_call - time.time(), self._run)
      self._timer.start()
      self.is_running = True

  def stop(self):
    self._timer.cancel()
    self.is_running = False

def save_datetime(file='date.txt', user=getpass.getuser()):
    with open(file, 'a+') as f:
        f.write('register: ' + user + '\t' + str(datetime.datetime.now().time()) + '\n')

if __name__ == '__main__':
    RepeatedTimer(1, save_datetime)

This creates an example text file like this:

register: james 11:51:54.988595
register: james 11:51:55.988939
register: james 11:51:56.988767

If you don't want milliseconds replace str(datetime.datetime.now().time()) with datetime.datetime.now().strftime('%H:%M:%S').

jimbob88
  • 697
  • 5
  • 20
0

input

 import datetime,time


 while True:
  current_time = datetime.datetime.now()
  print(current_time)
  time.sleep(1)

output

2022-02-18 04:39:56.781569
2022-02-18 04:39:57.782559
2022-02-18 04:39:58.783791
2022-02-18 04:39:59.785152
2022-02-18 04:40:00.785640
2022-02-18 04:40:01.786961
2022-02-18 04:40:02.788185
2022-02-18 04:40:03.788571
2022-02-18 04:40:04.789626
2022-02-18 04:40:05.790575
2022-02-18 04:40:06.791805
2022-02-18 04:40:07.793075
2022-02-18 04:40:08.794314
2022-02-18 04:40:09.795562
Bharath Kumar
  • 893
  • 9
  • 8