Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - time.time() and datetime.datetime.utcnow().timestamp() returning different Epochs

This is really two questions: 1st, are Epoch (Unix) timestamps the same on all machines (assuming their system clocks are correct), regardless of timezones?

I ask because I have code deployed to AWS Lambda that generates Epoch timestamps using the datetime module. When we extract the data, I am trying to convert to a local time string (also using datetime) and I am getting a 2 hour difference to what was expected. I then started testing the following code:

import datetime
import time

print(time.time()) #1
print(datetime.datetime.utcnow().timestamp()) #2

print#1: 1554747526.775873
print#2: 1554783526.775873

Running on my local machine, they are different by two hours. I deployed the above code to AWS Lambda and they return the same values. How is it different on my machine? The screenshot below shows the same code running on AWS Lambda (left) and my local machine. My system clock is correct.

time.time() vs datetime.utcnow().timestamp()

like image 735
dandev91 Avatar asked Apr 10 '19 01:04

dandev91


People also ask

What is the difference between datetime now and datetime UtcNow?

UtcNow tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer. DateTime. Now gives the date and time as it would appear to someone in your current locale.

How do I convert datetime to epoch time?

Convert from human-readable date to epochlong epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.

What does datetime timestamp return?

Datetime to Timestamp The timestamp() method of a datetime module returns the POSIX timestamp corresponding to the datetime instance. The return value is float. First, Get the current date and time in Python using the datetime. now() method.


1 Answers

The reason has to do with the timezone of your computer. The library time uses the timezone set in your computer, but in the case of the datetime library you're using the UTC timezone. In order to obtain the timestamp in the same timezone use datetime.datetime.now().timestamp()

like image 114
Alberto Bonsanto Avatar answered Oct 21 '22 03:10

Alberto Bonsanto