Jordan Keating
Jordan Keating

Reputation: 25

Converting datetime.datetime.second to an integer

I'm trying to convert datetime.datetime.second to an integer in Python 3. I would like to round this value and then use the integer value in the function datetime.time(hour=h,minute=m,second=s) where h, m and s represent integers. I'm currently getting an error message which reads as such:

    s = int(datetime.datetime.second)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'getset_descriptor'

Below is a snippet of my code which shows what I'm trying to do.

s = int(datetime.datetime.second)
#code to be added here should round s to nearest 0 or 5
m = int(datetime.datetime.minute)
h = int(datetime.datetime.hour)
t0 = datetime.time(hour=h,minute=m,second=s)

Please could someone explain why this type conversion does not work, what is datetime.datetime.second actually returning and what solutions there are to my problem.

I expected the code to return the number of seconds in the current time. E.g if it is 10:29:34 when the code is run I expected s to be set to 34. I was trying to round the number of seconds to 0 or 5. So in this case I expected to round the number of seconds to 35, then get the value for 10 and 29 and store them in h and m respectively. Then put those values in datetime.time() and display that time later in my code.

Upvotes: 1

Views: 3529

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122272

datetime.datetime.second does not give you the current time. It is not an object you generally want to use; it is an implementation detail of the datetime.datetime class.

To get the current time as a datetime.time() object, use the datetime.datetime.now() function, then use the .time() method on the returned datetime instance:

now = datetime.datetime.now().time()

Demo:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2018, 2, 6, 10, 29, 9, 758417)
>>> datetime.datetime.now().time()
datetime.time(10, 29, 11, 837654)

If you need to manipulate these values, you can use the time.replace() method to create a new datetime.time() instance with the updated value.

So to round your seconds value, you could use:

now = datetime.datetime.now().time()
now_rounded = now.replace(second=int(5 * round(now.second / 5)))  # round to nearest multiple of 5

To be precise, datetime.datetime.second, datetime.datetime.minute and datetime.datetime.hour are descriptor objects, letting you access the internal information of a datetime.datetime instance; it is these objects that make the attributes .second, .minute and .hour on instances of the datetime.datetime class:

>>> dt = datetime.datetime.now()
>>> dt.second
26
>>> datetime.datetime.second.__get__(dt, datetime.datetime)
26

Upvotes: 3

Related Questions