When I call on datetime.now() in my program it calls the current time, but when I call it again, it displays the previous time. How can I update datetime.now() so it calls the current time eachtime?
You say:
but when I call it again
... but you're NOT calling it again. You're more-than-likely printing/outputting the value of the variable that the first datetime.now() was assigned to.
Let's say you have the following:
from datetime import datetime
first_time = str(datetime.now())
print('First datetime.now() value: %s' % first_time)
You're probably attempting to get the updated time by simply printing first_time (what you incorrectly refer to as "calling").
Instead, you should either overwrite first_time by reassigning datetime.now() to it, or you should declare a new variable and assign datetime.now() to it.
# Overwriting & outputting:
# first_time = datetime.now()
# Declaring a new (updated) value (what I'll use in the example):
second_time = datetime.now()
# Outputting:
print('first_time: %s\nsecond_time: %s' % (str(first_time), str(second_time)))
You can define as follows:
def now():
return datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')
use the definition in the following way:
print('{}'.format(now()))
Related
I am following this answer and trying to call a variable of one function from another function, but getting an error. Below is my test code.
import datetime
from datetime import timedelta
import time
class TimeTesting:
def TimeTest1(self):
T1 = datetime.datetime.now()
time.sleep(5)
print('TimeTest1 is being called')
def TimeTest2(self):
T2 = datetime.datetime.now()
TimeDiff = T2 - self.T1
print('Timetest2 has been called')
print('Time diff is {}'.format(TimeDiff))
ob = TimeTesting()
ob.TimeTest1()
ob.TimeTest2()
Below is the error that I am getting -
TimeDiff = T2 - self.T1 AttributeError: 'TimeTesting' object has no
attribute 'T1'
Can someone point me out what I am doing wrong?
You would need to define T1 as an instance variable:
self.T1 = datetime.datetime.now()
As it stands, T1 is just a local variable to method TimeTest1, and is only in scope in that method.
I am trying to put this piece of code into a function so that i can avoid just copy pasting the code everytime. Here the code that I want to put in a function:
f= open("test.txt","w+")
os.chdir("//10.2.30.61/c$\Qlikview_Tropal/apps/ventes")
for fichiers in glob.glob("*"):
today = datetime.datetime.today()
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(fichiers))
duration = today - modified_date
if duration.days < 1:
f.write(f"{fichiers} = {duration} \n")
edit1: I have changed my code like Chepner's advice now the issue still remains that there is no output being written to my test.txt file.
What am I missing ?
Thanks alot!
As is, you don't need any parameters (though I'm going to re-write it slightly to use a with statement):
def my_function():
with open("test.txt", "w+") as f:
os.chdir("//10.2.30.61/c$\Qlikview_Tropal/apps/ventes")
for fichiers in glob.glob("*"):
today = datetime.datetime.today()
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(fichiers))
duration = today - modified_date
if duration.days < 1:
f.write(f"{fichiers} = {duration} \n")
my_function()
You might want to parameterize the function in several ways, however. Both the hard-coded output file name and the input directory are candidates.
def my_function(output_name, input_dir):
with open(output_name, "w+") as f:
os.chdir(input_dir)
for fichiers in glob.glob("*"):
today = datetime.datetime.today()
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(fichiers))
duration = today - modified_date
if duration.days < 1:
f.write(f"{fichiers} = {duration} \n")
my_function("test.txt", "//10.2.30.61/c$\Qlikview_Tropal/apps/ventes")
There's no one answer to this question. It depends on how you want to reuse this function. You can start by asking yourself these questions:
Will I always have to open the same file i.e. test.txt or if it not, you can set it as an argument.
Will I always change directory to the same folder i.e. "//10.2.30.61/c$\Qlikview_Tropal/apps/ventes"
Will I always write the same text to files i.e {fichiers} = {duration} \n
If these things change in different context, you can make them arguments. But, if everything will be the same, you can just define a function without any arguments.
If you just want to have a function without any parameter you can do like:
def my_function():
f= open("test.txt","w+")
os.chdir("//10.2.30.61/c$\Qlikview_Tropal/apps/ventes")
for fichiers in glob.glob("*"):
today = datetime.datetime.today()
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(fichiers))
duration = today - modified_date
if duration.days < 1:
f.write(f"{fichiers} = {duration} \n")
Call it simply like: my_function()
Function with parameters: Based on the code you have provided, you can keep file name and url as parameters to the function like:
Functions with parameters can be used again and again with different parameters
def my_function(fileName, URL):
f= open(fileName,"w+")
os.chdir(URL)
for fichiers in glob.glob("*"):
today = datetime.datetime.today()
modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(fichiers))
duration = today - modified_date
if duration.days < 1:
f.write(f"{fichiers} = {duration} \n")
Then call it like:
my_function("test.txt", "//10.2.30.61/c$\Qlikview_Tropal/apps/ventes")
I have a function that uses a datetime object as default value:
from datetime import datetime, timedelta
from random import randint
def getTime(date = datetime.now()):
i = randint(1,300)
date = date - timedelta(seconds = i)
return date
Now, I need to check if the date variable inside the function was given by another function or was used the default one datetime.now(). If was used the default one, then subtract i seconds, else return the date that was given.
You can do it as follows:
def my_function(date=None):
if date is None:
# The default is used
date = datetime.now()
...
Assuming that you want "now" to be computed every time:
def getTime(date=None):
return date or datetime.now() - timedelta(seconds=randint(1,300))
Otherwise:
Introduce a default arg:
def getTime(date=None, _default=datetime.now()):
return date or _default - timedelta(seconds=randint(1,300))
Or create a decorator:
def just_return_if_provided(f):
def inner(date=None):
return date or f(date)
return inner
#just_return_if_provided
def getTime(date=datetime.now()):
return date - timedelta(seconds=randint(1,300))
Something which I thought would be simple has become such a struggle.
I'm trying to format a datetime object.
From this 2016-06-17 09:56:53.289000+00:00 to 2016-06-17 09:56:53
This code I tried doesn't make any changes to the output. It skips right past it.
if type(field) is models.DateField:
if old_value != None:
old_value = old_value.strftime('%Y-%m-%d %H:%M:%S')[:-3]
if new_value != None:
new_value = new_value.strftime('%Y-%m-%d %H:%M:%S')[:-3]
Then I tried the following
if isinstance(new_value, datetime.datetime):
new_value = new_value.utcnow().strftime('%Y-%m-%d %H:%M:%S')[:-3]
if isinstance(old_value, datetime.datetime):
old_value = old_value.utcnow().strftime('%Y-%m-%d %H:%M:%S')[:-3]
However it removes any trace of the values of both new_value and old_value and displays nothing. Which is confusing me so much!
The end part of my code is as follows which displays the date:
if new_value != old_value:
print "%s does not match" % key
changes[key] = "Field %s %s updated to %s<br/>" % (key, old_value, new_value)
If anyone could point me in the right direction that would be great.
Try removing the .utcnow() call you added before your .strftime() calls. new_value.utcnow() invokes datetime.datetime.utcnow, which returns an entirely new datetime.datetime object representing the current time, which has nothing to do with new_value or old_value.
d = '2016-06-17 09:56:53.289000+00:00'
print(datetime.strptime(d[:19], '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S'))
Just a simple snippet based on your code
In [11]: from datetime import datetime
In [12]: mytime = now.strftime("%Y-%m-%d %H:%M:%S")
In [13]: print(mytime)
2016-06-21 16:44:32
I need to pass some function as argument in another function. So, I want to add current time to class attribute every second, for example
import time
class Measurement():
values = []
def add_value(self, value):
print "added value"
self.values.append(value)
def smart_delay(input_function,args):
start_time = time.time()
while 5 > (time.time() - start_time):
print "Calling function"
input_function(args)
time.sleep(1)
measurement = Measurement()
smart_delay(measurement.add_value,time.time())
Ok, but after checking contents of measurement.values, I get
[1425980407.173, 1425980407.173, 1425980407.173, 1425980407.173] - so values are the same!!!
What happened? And how to get proper values?
Updated:
Actually, this question is about the way to allow to call some function, passed as the argument to another function. What do you think about this:
import time
class Measurement():
values = []
def add_value(self, value):
print "added value"
self.values.append(value)
def smart_delay(input_function):
start_time = time.time()
while 5 > (time.time() - start_time):
print "Calling function"
input_function()
time.sleep(1)
measurement = Measurement()
smart_delay(lambda: measurement.add_value(time.time()))
Your call to time.time() is executed before the call to smart_delay(...), so smart_delay(measurement.addvalue, time.time()) will first get the return value from time.time() and pass that forward to smart_delay.
You need to pass the time.time function itself, and call it inside of the smart_delay method, instead of passing its return value:
import time
class Measurement():
values = []
def add_value(self, value):
print "added value"
self.values.append(value)
def smart_delay(output_f, input_f):
start_time = time.time()
while 5 > (time.time() - start_time):
print "Calling function"
output_f(input_f())
time.sleep(1)
measurement = Measurement()
smart_delay(measurement.add_value, time.time)
Notice, that this is not the best way to do what you're doing, but it works.
Here's how I'd do it:
import time
# Why do you need a measurement class which only acts as a list anyways?
my_measurements = []
def repeat(duration, function, args=(), kwargs={}, interval=1):
"""Repeat a function call for the given duration."""
start_time = time.time()
while duration > time.time() - start_time:
function(*args, **kwargs)
time.sleep(interval)
def add_time_measurement(measurements):
measurements.append(time.time())
repeat(5, add_time_measurement, (my_measurements,))
And if you want some prints, you can just add them in the add_time_measurement function.