1

I am building a custom module (let's call it test_mod) for my files where I define a backup path with a timestamp:

from datetime import datetime

class Backup:
    Timestamp = datetime.now()

Using import test_mod and calling test_mod.Backup.Timestamp will return me the timestamp of the moment when the module was imported, but as I call the attribute again and again, the timestamp remains the same.

Why is that and what should I do if I want to make the .Timestamp atribute update whenever I call it?

manoelpqueiroz
  • 575
  • 1
  • 7
  • 17

3 Answers3

2

I think it is not a problem of your module instead of your class Backup. You should put the initialization of Timestamp to the __init__ method os your class.

This method is the initialization method of your class and is called every time you create a new object of type Backup.

class Backup:
    def __init__(self):
        self.Timestamp = datetime.now()

I get different timestamps with this solution.

If you initialize a class variable outside the __init__() function the variable is shared by all classes and you get the same timestamp from each object of type Backup.

Link: Variables inside and outside of a class __init__() function

When you want the current timestamp you could wrap the datetime.now() into a new function of your class Backup.

lghh
  • 184
  • 1
  • 11
  • I do like this solution. But now let's say I have a method `test(self)` with `return 'a string' + str(self.Timestamp)`; it outputs a `TypeError: test() missing 1 required positional argument: 'self'` (using `str(Timestamp)` also gives this error), how should that be handled? – manoelpqueiroz Apr 19 '19 at 21:22
  • Could you post the whole class definition? I can't the an problem. – lghh Apr 21 '19 at 12:03
1

You saved the value of datetime.now() into an attribute. This means, that you called the method at the creation of the class instance and saved the return value into an attribute.

You should call datetime.now() inside a method / function if you want the timestamp to always be actual.

dodekja
  • 537
  • 11
  • 24
0

if you want to use it as an attribute rather than a method i.e if you prefer Backup().Timestamp rather than Backup().Timestamp(), you should use @property

from datetime import datetime from time import sleep

class Backup:
    @property
    def time_stamp(self):
        return datetime.now()

to test it:

b = Backup()

print(b.time_stamp)
sleep(1)
print(b.time_stamp)

output:

2019-04-19 18:29:20.207778
2019-04-19 18:29:21.207825
Mahmoud Elshahat
  • 1,873
  • 10
  • 24