Python Datetime Merging all values into int

Viewed 87

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?

2 Answers

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

you can use indexing or run through a it as a string.

import datetime
s = str(datetime.datetime.utcnow())
chars_list = ['-', ' ', ':', '.']
ans = ''
for c in s:
    if c not in chars_list:
        ans = ans + c
print(int(ans))
Related