How to convert datetime to integer in python

后端 未结 4 505
无人共我
无人共我 2020-12-03 07:14

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

4条回答
  •  Happy的楠姐
    2020-12-03 07:26

    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"))
    

提交回复
热议问题