Possible Duplicate:
Python datetime to Unix timestamp
Is there a way to convert a datetime
to int
, representing the minutes since, for example, January 2012, so that this int
can be modified, written to a database, compared and so on?
EDIT:
The server I am running this on uses Python 2.6.6
Subtracting two datetime.datetime
objects gives you a timedelta
object, which has a .total_seconds()
method (added in Python 2.7). Divide this by 60 and cast to int()
to get minutes since your reference date:
import datetime
january1st = datetime.datetime(2012, 01, 01)
timesince = datetime.datetime.now() - january1st
minutessince = int(timesince.total_seconds() / 60)
or in a python shell:
>>> import datetime
>>> january1st = datetime.datetime(2012, 01, 01)
>>> timesince = datetime.datetime.now() - january1st
>>> minutessince = int(timesince.total_seconds() / 60)
>>> minutessince
346208
For python 2.6 and earlier, you'll have to use the .days
and .seconds
attributes to calculate the minutes:
minutessince = timesince.days * 1440 + timesince.seconds // 60
which gives you an integer as well.
If you want the minutes of the delta between two dates, you can make a datetime.timedelta
object by subtracting the two dates (see here), and then retrieve the minutes as shown in this question:
Convert a timedelta to days, hours and minutes
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