How to Convert Datetime to Integer in Python

How to convert datetime to integer in python

It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetime module (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp()).

If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:

2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)

def to_integer(dt_time):
return 10000*dt_time.year + 100*dt_time.month +


In [1]: import datetime

In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def to_integer(dt_time):
: return 10000*dt_time.year + 100*dt_time.month +
: # Or take the appropriate chars from a string date representation.

In [3]: to_integer(, 6, 13))
Out[3]: 20120613

If you also want minutes and seconds, then just include further orders of magnitude as needed to display the digits.

I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.

It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.

Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.

It's generally much better to leave the value in a date context, like, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.

Converting days (datetime) to integer in python?

If you're looking for difference in days, Timedelta objects have .days property:

daysLeft_to_delete = 1000 - diff.days

How can I convert a date variable into "int" in Python?

You can do :

df['date_new'] = df['date'].str.replace('\D', '').astype(int)


1.'\D' replaces all non-digit characters with ''.

2. Finally, we convert the resultant string to integer with astype.

Here's a dummy example:

df = pd.DataFrame({'date' : pd.date_range('10/1/2018', periods=10, freq='H')})
df['date'] = df['date'].astype(str)
df['new_date'] = df['date'].str.replace('\D', '').astype(int)

date new_date
0 2018-10-01 00:00:00 20181001000000
1 2018-10-01 01:00:00 20181001010000
2 2018-10-01 02:00:00 20181001020000
3 2018-10-01 03:00:00 20181001030000
4 2018-10-01 04:00:00 20181001040000
5 2018-10-01 05:00:00 20181001050000
6 2018-10-01 06:00:00 20181001060000
7 2018-10-01 07:00:00 20181001070000
8 2018-10-01 08:00:00 20181001080000
9 2018-10-01 09:00:00 20181001090000

Convert a date into an integer in python

you can edit as below.

if calculateAge(date1) < 18:
print('You are under age')

enter image description here

How to convert integer timestamp into a datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

Related Topics

Leave a reply