Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a datetime object to an integer python

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'

like image 485
user4690602 Avatar asked Mar 24 '15 16:03

user4690602


People also ask

How to convert an integer to a date object in Python?

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.

How to convert datetime to integer UTC timestamp in Python?

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 ().

How to convert datetime to an integer in Java?

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!

How do I get the current date and time in Python?

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.


1 Answers

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)
like image 146
Molek Avatar answered Oct 22 '22 21:10

Molek