26

How to get timestamp from the structure datetime? What is right alternative for non-existing datetime.utcnow().timestamp()?

kyb
  • 7,233
  • 5
  • 52
  • 105
  • 1
    This answer below is much simpler than the accepted: https://stackoverflow.com/a/56689007/3559330 – mattyb May 21 '21 at 23:20

5 Answers5

60

use time, and int to remove the milliseconds

from time import time 

int(time())

# 1561043225
Alex
  • 5,759
  • 1
  • 32
  • 47
12
import time,datetime
time.mktime(datetime.datetime.today().timetuple())
galaxyan
  • 5,944
  • 2
  • 19
  • 43
  • 1
    Very cumbersome solution. As python. Many operations for such small work. C has time() and it works like a charm :) – kyb Sep 02 '16 at 14:11
10

There is another stupid trick - achieve timedelta

(datetime.utcnow()-datetime(1970,1,1,0,0,0)).total_seconds()

found here. Better

(datetime.utcnow()-datetime.fromtimestamp(0)).total_seconds()

And this solution contains subseconds.

Community
  • 1
  • 1
kyb
  • 7,233
  • 5
  • 52
  • 105
9

If you don't have to get timestamp from structure datetime, you can decrease instruction like this

import time
print time.time()
Damotorie
  • 586
  • 7
  • 25
-3

If I understand correctly what sort of output you are seeking:

from datetime import datetime
timestamp = datetime.now().strftime("%H:%M:%S")
print(timestamp)

> 11:44:40

EDIT: Appears I misinterpreted your question? You are asking for the naive universal time, then galaxyan's answer is concise.

Konchshell
  • 102
  • 2
  • 11