# [python] How to convert datetime to integer in python

how can i convert YYYY-MM-DD hh:mm:ss format to integer in python? for example 2014-02-12 20:51:14 -> to integer.

i know how to convert only hh:mm:ss but not yyyy-mm-dd hh:mm:ss

``````def time_to_num(time_str):
hh, mm , ss = map(int, time_str.split(':'))
return ss + 60*(mm + 60*hh)
``````

This question is related to `python` `datetime` `integer` `converter`

## The answer is

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

#### Explanatory Code

``````dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))
``````

#### General Function

To avoid that doing manually use below function

``````def datetime_to_int(dt):
return int(dt.strftime("%Y%m%d%H%M%S"))
``````

This in an example that can be used for example to feed a database key, I sometimes use instead of using AUTOINCREMENT options.

``````import datetime

dt = datetime.datetime.now()
seq = int(dt.strftime("%Y%m%d%H%M%S"))
``````

I think I have a shortcut for that:

``````# Importing datetime.
from datetime import datetime

# Creating a datetime object so we can test.
a = datetime.now()

# Converting a to string in the desired format (YYYYMMDD) using strftime
# and then to int.
a = int(a.strftime('%Y%m%d'))
``````