331

Python provides different packages (datetime, time, calendar) as can be seen here in order to deal with time. I made a big mistake by using the following to get current GMT time time.mktime(datetime.datetime.utcnow().timetuple())

What is a simple way to get current GMT time in Unix timestamp?

nmichaels
  • 49,466
  • 12
  • 107
  • 135
Cory
  • 14,865
  • 24
  • 57
  • 72
  • 4
    What are input/output? `datetime.utcnow()` returns current UTC time as datetime object (I assume you want UTC when you are talking about "GMT time"). `time.time()` returns Unix timestamp directly as float number. Here's [how to convert datetime.date/datetime.datetime representing time in UTC to POSIX timestamp](http://stackoverflow.com/a/8778548/4279). – jfs May 26 '13 at 01:48
  • Is your proposed method wrong, or just too verbose? Related: http://stackoverflow.com/questions/15940280/how-to-get-utc-time-in-python – Ciro Santilli OurBigBook.com Dec 05 '15 at 16:21
  • 3
    Why was your method a mistake? – skeller88 Dec 12 '17 at 23:10
  • the idea of the unix count is that it's the same in all time zones – sivi Jan 12 '23 at 16:56

10 Answers10

382

I would use time.time() to get a timestamp in seconds since the epoch.

import time

time.time()

Output:

1369550494.884832

For the standard CPython implementation on most platforms this will return a UTC value.

Edmond Burnett
  • 4,829
  • 3
  • 18
  • 17
  • 30
    The catch is that your machine's local clock may be not in UTC. – 9000 May 26 '13 at 07:00
  • 2
    @9000: Correct, although I would always insist on UTC in any environment where time keeping mattered. And he did ask for the simplest solution. Note that with CPython on modern platforms, including Linux, BSD, Mac OS X, and Windows, will all return UTC for time.time(). This mirrors the behavior of the C standard library's time function on these OS's. – Edmond Burnett May 26 '13 at 07:21
  • 124
    @9000: local timezone doesn't matter. Unix time corresponds to UTC time (if we ignore the time around leap seconds). Think about it: the timestamp is the number of seconds elapsed since the epoch (a fixed moment in time): why would it depend on what timezone machine's local clock uses? At any given moment in time the Unix time is the same around the world. Some (unknown) platform might use a different epoch, but its value still wouldn't be dependent on the local timezone. – jfs May 26 '13 at 08:32
  • 2
    http://stackoverflow.com/questions/13890935/does-pythons-time-time-return-the-local-or-utc-timestamp – Ciro Santilli OurBigBook.com Dec 05 '15 at 16:19
  • @jfs a fixed moment of time, and space, remember time is relative. It is impossible to define moments that happen at the same time – Rainb Jan 04 '21 at 12:12
  • 2
    @Rainb: special relativity has nothing to do with my comment (no relation to local time zones whatsoever) – jfs Jan 05 '21 at 14:55
  • If you multi-boot, some operating systems might synchronize your hardware clock to "local time" not realizing that this makes other ones report the wrong number of seconds since the epoch. – MatrixManAtYrService Feb 16 '21 at 05:00
  • I think this solution has a problem. This depends on local timezone. For example, in my local environment, the result of `(time.time() - datetime.datetime.utcnow().timestamp()) / 3600` is about 9.0 with Japanese timezone (UTC+9). – iwataka Nov 02 '22 at 04:58
  • well, if `time.time()` returns UTC time difference, then it includes *leap seconds* while unix time does NOT. So technically they are not the same but may not matter for your use-case. – C S Jan 17 '23 at 19:15
  • @Rainb, jfs wasn't talking about simultaneous events. There was one event, namely the Unix epoch, which took place a known amount of time ago from the Earth's reference frame. It would be fairly difficult to determine where that was spatially, relative to where we are now, and wouldn't affect the problem at hand. – SO_fix_the_vote_sorting_bug Feb 26 '23 at 03:47
298
import time

int(time.time()) 

Output:

1521462189
Max
  • 4,292
  • 1
  • 20
  • 14
61

python2 and python3

it is good to use time module

import time
int(time.time())

1573708436

you can also use datetime module, but when you use strftime('%s'), but strftime convert time to your local time!

python2

from datetime import datetime
datetime.utcnow().strftime('%s')

python3

from datetime import datetime
datetime.utcnow().timestamp()
MikA
  • 5,184
  • 5
  • 33
  • 42
  • 12
    Being in UTC+1, `time.time()` and `datetime.utcnow().timestamp()` do *not* give the same value! – user136036 Dec 31 '19 at 15:42
  • 1
    Also although I expected the 2nd option to be correct, I had to use datetime.now().timestamp() to get the correct value in UTC+1100. I expected timestamp() to work correctly for either but it doesn't seem to – David Waterworth Jan 28 '20 at 23:04
  • 2
    Looking closer, both datetime.utcnow() and datetime.now() return a naive datetime (no tzinfo), and timestamp() appears to assume local when tzinfo=null. – David Waterworth Jan 28 '20 at 23:34
  • 2
    If you get this timestamp to use it to another system which expects real true Unix timestamp of Epoch time you better go with `datetime.now().timestamp()` otherwise the other is shifted. In my humble opinion I agree with @DavidWaterworth that no matter what the timezone is, the timestamp should have always bring back the same Long number is seconds – George Pligoropoulos Dec 26 '20 at 14:02
  • 2
    This is a wrong answer. `datetime.utcnow().timestamp()` returns a wrong result unless your're in UTC+00 tz. `datetime.now().timestamp()` is correct. – Raz Apr 12 '22 at 13:18
58

Does this help?

from datetime import datetime
import calendar

d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime

How to convert Python UTC datetime object to UNIX timestamp

Nick Caplinger
  • 784
  • 6
  • 10
  • @Cairnarvon That was just an example. If you want current timestamp then you can simply call `time.time()` and need no datetime conversion at all. – Messa Aug 24 '16 at 11:48
  • 2
    FWIW: That is not the UTC Time, it is UTC converted to local time. To get a timestamp in UTC you have to do somethin else. – Sherlock70 Nov 03 '17 at 09:00
49

Python 3 seconds with microsecond decimal resolution:

from datetime import datetime
print(datetime.now().timestamp())

Python 3 integer seconds:

print(int(datetime.now().timestamp()))

WARNING on datetime.utcnow().timestamp()!

datetime.utcnow() is a non-timezone aware object. See reference: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects

For something like 1am UTC:

from datetime import timezone
print(datetime(1970,1,1,1,0,tzinfo=timezone.utc).timestamp())

or

print(datetime.fromisoformat('1970-01-01T01:00:00+00:00').timestamp())

if you remove the tzinfo=timezone.utc or +00:00, you'll get results dependent on your current local time. Ex: 1am on Jan 1st 1970 in your current timezone - which could be legitimate - for example, if you want the timestamp of the instant when you were born, you should use the timezone you were born in. However, the timestamp from datetime.utcnow().timestamp() is neither the current instant in local time nor UTC. For example, I'm in GMT-7:00 right now, and datetime.utcnow().timestamp() gives a timestamp from 7 hours in the future!

C-Otto
  • 5,615
  • 3
  • 29
  • 62
Stan Kurdziel
  • 5,476
  • 1
  • 43
  • 42
27

Or just simply using the datetime standard module

In [2]: from datetime import timezone, datetime
   ...: int(datetime.now(tz=timezone.utc).timestamp() * 1000)
   ...: 
Out[2]: 1514901741720

You can truncate or multiply depending on the resolution you want. This example is outputting millis.

If you want a proper Unix timestamp (in seconds) remove the * 1000

Maresh
  • 4,644
  • 25
  • 30
  • You code very specifically is forcing the time into an integer so I'm confused why the output text is a decimal number? – Weston Dec 30 '17 at 13:50
  • ye my bad, I added the int casting later – Maresh Jan 02 '18 at 14:01
  • This is the exact equivalent of Javascript `moment` library's `moment().utc().valueOf()`. Exactly what I was looking for. Thanks – azhar22k Oct 19 '18 at 12:19
  • UNIX timestamp is supposed to be **seconds** since 1970. Your solution doesn't produce this. – skyking Jan 29 '19 at 21:17
  • 2
    "You can truncate or multiply depending on the resolution you want" Drop the * 1000 part and you get seconds. – Maresh Jan 30 '19 at 14:19
6

At least in python3, this works:

>>> datetime.strftime(datetime.utcnow(), "%s")
'1587503279'
usernamenumber
  • 149
  • 1
  • 8
3

I like this method:

import datetime, time

dts = datetime.datetime.utcnow()
epochtime = round(time.mktime(dts.timetuple()) + dts.microsecond/1e6)

The other methods posted here are either not guaranteed to give you UTC on all platforms or only report whole seconds. If you want full resolution, this works, to the micro-second.

Community
  • 1
  • 1
vschmidt
  • 63
  • 7
  • 1
    Unfortunately this doesn't seem to give UTC unless you happen to be in a UTC+0000 timezone. Using `utctimetuple` instead does the trick though. – skyking Jan 29 '19 at 21:16
3
from datetime import datetime as dt
dt.utcnow().strftime("%s")

Output:

1544524990
2ni
  • 507
  • 1
  • 5
  • 13
2
#First Example:
from datetime import datetime, timezone    
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)

Output: 1572878043380

#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)

Output: 1572878043

  • Here, we can see the first example gives more accurate time than second one.
  • Here I am using the first one.
Chandan Sharma
  • 2,321
  • 22
  • 22