How do I get seconds since 1/1/1970 of a Python datetime object?

Question:

I’m using Python 3.7 and Django. I wanted to get the number of seconds (or milliseconds) since 1/1/1970 for a datetime object. Following the advice here — In Python, how do you convert a `datetime` object to seconds?, I implemented

now = datetime.now()
...
return [len(removed_elts) == 0, score, now.total_seconds()]

but the “now.total_seconds()” line is giving the error

AttributeError: 'datetime.datetime' object has no attribute 'total_seconds'

What’s the right way to get the seconds since 1/1/1970?

Asked By: Dave

||

Answers:

now = datetime.now()
...
return [len(removed_elts) == 0, score, now.timestamp()]
Answered By: ababak

This should work.

import datetime
first_date = datetime.datetime(1970, 1, 1)
time_since = datetime.datetime.now() - first_date
seconds = int(time_since.total_seconds())
Answered By: Sahil
import time
print(time.time())

Output:

1567532027.192546
Answered By: Alderven

You can try:

import datetime

now = datetime.datetime.now()
delta = (now - datetime.datetime(1970,1,1))
print(delta.total_seconds())

now is of type datetime.datetime and has no .total_seconds() method.

delta is of type datetime.timedelta and does have a .total_seconds() method.

Hope this helps.

Answered By: René

In contrast to the advice you mentioned, you don’t call total_seconds() on a timedelta object but on a datetime object, which simply doesn’t have this attribute.

So, one solution for Python 3.7 (and 2.7) could for example be:

import datetime

now = datetime.now()
then = datetime.datetime(1970,1,1)
...
return [len(removed_elts) == 0, score, (now - then).total_seconds()]

Another shorter but less clear (at least on first sight) solution for Python 3.3+ (credits to ababak for this one):

import datetime

now = datetime.now()
...
return [len(removed_elts) == 0, score, now.timestamp()]
Answered By: jofrev