Home > Enterprise >  ValueError: invalid literal for int() with base 10: '10/24/2021, 02:49:28'
ValueError: invalid literal for int() with base 10: '10/24/2021, 02:49:28'

Time:10-25

I am currently trying to write an simple script which is adding one day to the current date. But when running my script it errors out like this: ValueError: invalid literal for int() with base 10: '10/24/2021, 02:49:28'

This is the full error message:

Traceback (most recent call last):
  File "test.py", line 7,
    a = int(a)   timedelta(str(nt))
ValueError: invalid literal for int() with base 10: '10/24/2021, 02:49:28'

This is my code:

from datetime import datetime
from datetime import timedelta

nt = '1'
a = datetime.now()
a = a.strftime("%m/%d/%Y, %H:%M:%S")
a = int(a)   timedelta(str(nt))
print(a)

Am I doing something wrong in my code? If so I would be very glad if someone could explain to me what I've made wrong and help me fix this problem.

Thank's for every help and suggestion in advance:)

Ps: Feel free to question if something is unclear:)

CodePudding user response:

If you want to get the integer value of a string, that's the way, yes, but it does need to actually be a valid integer.

print (int("22"))

22

And if turning the string into a number doesn't work, it gives that exception that you just saw.

try:
    int('Your string here')
except Exception as e:
    print(e)

invalid literal for int() with base 10: 'Your string here'

You're doing weird things with the variable a. Calling a function is normal. But assigning the return value of that function to a wipes out the original datetime object. If you want to print out the time, then just print it.

from datetime import datetime, timedelta

a = datetime.now()
print ('printout of a timestamp:', a.strftime("%m/%d/%Y, %H:%M:%S"))

printout of a timestamp: 10/23/2021, 23:27:51

If you want a timedelta, use the parameters it provides. It's much clearer if you just use timedelta(days=1)

a  = timedelta(days=1)
print ('one second later it is: ', a.strftime("%m/%d/%Y, %H:%M:%S"))

one second later it is: 10/24/2021, 23:27:51

CodePudding user response:

You are trying to convert datetime object to int object, which will raise error. If you want to add or subtract dates, then use the timedelta() method. Enter the seperation value between dates as timedelta(days=1) and add it or subtract it to the current datetime object. Your code:

from datetime import datetime
from datetime import timedelta

a = datetime.now()
a = a   timedelta(days=1)
a = a.strftime("%m/%d/%Y, %H:%M:%S")  #converted to string format

print(a)
  • Related