4

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?

Dave
  • 15,914
  • 110
  • 364
  • 695
  • 1
    I think you are only having a problem because you didn't subtract the `datetime` objects to get a `timedelta` object (which does have an attribute `total_seconds`). I believe that [this answer](https://stackoverflow.com/a/7852969/5982697) on the question you linked does what you want. But you can also use [`datetime.timestamp`](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp) as mentioned below. – Heath Sep 03 '19 at 14:44

5 Answers5

2

This should work.

import datetime
first_date = datetime.datetime(1970, 01, 01)
time_since = datetime.datetime.now() - first_date
seconds = int(time_since.total_seconds())
Sahil
  • 1,296
  • 13
  • 33
2
import time
print(time.time())

Output:

1567532027.192546
Alderven
  • 6,120
  • 4
  • 22
  • 35
2

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()]
jofrev
  • 324
  • 3
  • 11
1
now = datetime.now()
...
return [len(removed_elts) == 0, score, now.timestamp()]
ababak
  • 1,552
  • 1
  • 10
  • 23
1

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.

Rene
  • 3,062
  • 3
  • 17
  • 41