Convert DateTimeField to Django on Unix

In my Django project, I use DateTimeFieldin the model. It essentially has python instances datetime.datetime.

What is the fastest way to convert this in time from era (in seconds)?

+4
source share
2 answers

In Python 3.3+, you can use datetime.timestamp():

>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0

For an earlier version of Python, you can:

# Format it into seconds
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'

# OR, subtract the time with 1 Jan, 1970 i.e start of epoch time
# get the difference of seconds using `total_seconds()`
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0
+8
source
datetime.datetime(date).strftime('%s')

I think this will work for you.

+3
source

Source: https://habr.com/ru/post/1661059/


All Articles