I would like to convert a datetime object to an int in python:
import datetime
time_entered = datetime.datetime.strptime(raw_input("Time1: "), "%H%M")
time_left = datetime.datetime.strptime(raw_input("Time2"), "%H%M")
time_taken = time_left - time_entered
int(time_taken)
When I run that code I get the following error:
TypeError: int() argument must be a string or a number, not 'datetime.timedelta'
How to convert an integer into a date object in Python? Python Server Side Programming Programming You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp.
First, we enter the UTIC time inside the datetime.datetime () object. Then we pass the object to d.timtuple () function which gives a tuple containing the parameters like year, month, day, and so on, and then using the calendar function we convert the datetime to integer UTC timestamp. First, we get the current time using datetime.datetime.now ().
In this method, we are using strftime () function of datetime class which converts it into the string which can be converted to an integer using the int () function. Returns : It returns the string representation of the date or time object. Attention geek!
Here we import the DateTime module to use the DateTime function from it. And then use datetime.now () function to get the current date and time. Convert the DateTime object into timestamp using DateTime.timestamp () method. We will get the timestamp in seconds.
You can convert the datetime object to a timetuple, and then use the time.mktime function
import time
from datetime import datetime
timestamp = int(time.mktime(datetime.now().timetuple()))
Convert it back with:
now = datetime.fromtimestamp(timestamp)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With