Search code examples
pythonpython-3.xpython-datetime

Python Datetime Merging all values into int


I would like to get the datetime of the program converted to a int, What I want is:

import datetime
print(datetime.datetime.utcnow())

> 2021-01-12 09:15:16.9791000 # the time I ran the command

into this:

> 202101120915169791000

How can I do this?


Solution

  • Use strftime format.

    import datetime
    a = datetime.datetime.utcnow()
    a = int(a.strftime('%Y%m%d%H%M%S'))
    print(a)
    
    # Output
    # 20210112092900
    

    If you want to get the whole nanosecond then try it

    print(int(a.strftime('%Y%m%d%H%M%S%f')))
    # Output
    #20210112092900275246