From datetime to timestamp python - python

I need to convert a datetime object with microsecond resolution to a timestamp, the problem is that I don't get the same timestamp second's resolution.
For example the timestamp that I pass as an argument is 1424440192 and I get in return 1424429392.011750, why is this?, I Only changed microsecond value of the datetime object, so I expect to change only values after the dot.
PD: In this example I'm only simulating one timestamp.
from datetime import datetime, timedelta
def totimestamp(dt, epoch=datetime(1970,1,1)):
td = dt - epoch
return td.total_seconds()
#return (td.microseconds + (td.seconds + td.days * 24 * 3600) *
#10**6) / 1e6
timestamp_pc = 1424440192
tm = datetime.fromtimestamp(timestamp_pc)
new_tm = tm.replace(microsecond = 11750)
print tm
print new_tm
print timestamp_pc
print "%f " %(totimestamp(new_tm))

I get it.
I changed
tm = datetime.fromtimestamp(timestamp_pc)
for
tm = datetime.utcfromtimestamp(timestamp_pc)
and now timestamp are identical.

From the fromtimestamp documentation:
If optional argument tz is None or not specified, the timestamp is converted to the platform’s local date and time, and the returned datetime object is naive.
Since your totimestamp function does not do the same timezone adjustment in reverse, the time is wrong by your time zone offset.

Related

Why aren't identical datetimes equal?

I'm working on a simple Python3 script that considers data in five-minute increments. Thanks to this post, I have code which takes any Python datetime object and then rounds it down to the nearest five minutes. (:00, :05, :10, :15, etc.) Note that I cannot use pandas.
Now I need to be able to compare that "rounded-down" datetime with other datetimes, and here I'm running into a problem. Consider this test code:
import sys
from datetime import datetime
from datetime import timedelta
def roundDownDateTime(dt):
# Arguments:
# dt datetime object
delta = timedelta(minutes=1) * (dt.minute % 5)
return dt - delta
def testAlarm(testDate):
# Arguments:
# testDate datetime object
currDate = roundDownDateTime( datetime.now() ) # currDate is a DateTime object, rounded down to 5 mins
print("currDate: "+currDate.strftime("%Y%m%d%H%M"))
print("testDate: "+testDate.strftime("%Y%m%d%H%M"))
if(currDate == testDate):
print("ALARM!!!!")
def main():
testDate = datetime.strptime(sys.argv[1], "%Y%m%d%H%M")
testAlarm(testDate)
if __name__ == "__main__":
main()
The code does all of the following:
The main() function takes a string you enter on the command line,
then converts it into a "%Y%m%d%H%M" datetime
Your datetime is rounded down to the last five minute increment
In testAlarm(), your date is compared with the current date, also in
"%Y%m%d%H%M" format, also rounded down five minutes.
If the current date matches the cmd line argument, you should get an
"ALARM!!! in the output.
Here's the actual output, run on my Ubuntu machine:
me#unbuntu1$ date
Tue Jan 17 14:27:41 UTC 2023
me#unbuntu1$
me#unbuntu1$ python3 toy04.py 202301171425
currDate: 202301171425
testDate: 202301171425
me#unbuntu1$
Okay: Although I'm rounding down my date to match the "rounded-down" version of the current date, the if(currDate == testDate): line of code is still evaluating to False. While both datetimes appear equal in the "%Y%m%d%H%M" format, they are somehow not equal.
My first thought was that maybe the "rounded down" datetime still retained some residual seconds or microseconds even after the rounding part? So I modified my function to this:
def roundDownDateTime(dt):
# Arguments:
# dt DateTime object
delta = timedelta(minutes=1) * (dt.minute % 5)
dt = dt - delta
dt.replace(second=0, microsecond=0)
return dt
But that makes no difference; I still get the exact same output as before.
Normally, you would only care if currDate > testDate for alarming purposes. But in my case, I must be able to compare datetimes for equality after one (or more) of them has been through the roundDownDateTime() function. What am I missing? Is my roundDownDateTime() function faulty? Thank you.
dt.replace returns a new datetime object; it does not modify dt in place.
def roundDownDateTime(dt):
# Arguments:
# dt DateTime object
delta = timedelta(minutes=1) * (dt.minute % 5)
dt = dt - delta
return dt.replace(second=0, microsecond=0)

How to minus time that received from API server and current time in Python

Kindly help below my query:
I got an estimated time from API server like below:
2019-09-25T20:11:23+08:00
it seems like iso 8601 standard with timezone.
I would like to know how to calculate how many days, hours, minutes and seconds left from above value to the current time.
import datetime
Receved_time_frim_API = "2019-09-25T20:11:23+08:00"
Current_time = datetime.datetime.now()
left_days =
left_hour =
left_min =
left_sec =
Your time string contains timezone info. According to https://stackoverflow.com/a/13182163/12112986 it's easy to convert it to datetime object in python 3.7
import datetime
received = datetime.datetime.fromisoformat(Receved_time_frim_API)
In previous versions there is no easy oneliner to convert string with timezone to datetime object. If you're using earlier python version, you can try something crude, like
>>> date, timezone = Receved_time_frim_API.split("+")
>>> tz_hours, tz_minutes = timezone.split(":")
>>> date = datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S")
>>> date -= datetime.timedelta(hours=int(tz_hours))
>>> date -= datetime.timedelta(minutes=int(tz_minutes))
Note that this will work only in case of positive timezones
To substract two datetime objects use
td = date - Current_time
left_days = td.days
left_hour = td.seconds // 3600
left_min = (td.seconds//60)%60
left_sec = td.seconds % 60
Okay first you need to parse the Receved_time_frim_API into datetime format:
from dateutil import parser
Receved_time_frim_API = parser.parse("2019-09-25T20:11:23+08:00")
But you can't just substract this from your Current_time, because datetime.now() is not aware of a timezone:
from datetime import timezone
Current_time = datetime.datetime.now().replace(tzinfo=timezone.utc)
print (Current_time-Receved_time_frim_API)
The result is a datetime.timedelta

timedelta.seconds is returning a wrong value

I need to get time difference in seconds. But my function returns huge values, which I assume are microseconds. When I try to put days, I get -1 value. Can someone tell me how to get the difference in seconds.
This is my code:
from datetime import datetime, date, time, timedelta
time_now2 = datetime.strptime(time_now, "%Y-%m-%d %H:%M:%S.%f")
lt2 = datetime.strptime(LT, "%Y-%m-%d %H:%M:%S.%f")
ftime = lt2 + timedelta(seconds = 1200)
waiting_time = (time_now2 - ftime).seconds
Instead of waiting_time = (time_now2 - ftime).seconds, could you try using total_seconds, instead, i.e. (time_now2 - ftime).total_seconds()?

add 2 hours in current time in Python and print the time in timestamp

How to get the current time and return that in timestamp format after adding 2 hours in it like 1535020200000
i tried the following but I am not getting the expected result
current_time + timedelta(hours=2)
(datetime.now()).split('.')[0] + timedelta(hours=2)
since the second one returns a string, addition operation cannot be done
I would recommend the following
from datetime import datetime, timedelta
two_hours_from_now = datetime.now() + timedelta(hours=2)
print(two_hours_from_now.timestamp())
You can do as follow:
import datetime
current_time = datetime.datetime.now()
later = current_time + datetime.timedelta(hours=2)
print(later.timestamp())
You get:
1535031690.031316
Quoting the documentation:
Return POSIX timestamp corresponding to the datetime instance. The return value is a float similar to that returned by time.time().
If you need a timestamp, use time.time:
current_plus_2_hours = time.time() + 2 * 60 * 60
thanks to all of you, though this worked for me
start_at = 2
hours_from_now = int(str(time.time() + start_at * 60 * 60)[0:10]) * 1000

Seconds since date (not epoch!) to date

I have a dataset file with a time variable in "seconds since 1981-01-01 00:00:00".
What I need is to convert this time into calendar date (YYYY-MM-DD HH:mm:ss).
I've seen a lot of different ways to do this for time since epoch (1970) (timestamp, calendar.timegm, etc) but I'm failing to do this with a different reference date.
I thought of doing something that is not pretty but it works:
time = 1054425600
st = (datetime.datetime(1981,1,1,0,0)-datetime.datetime(1970,1,1)).total_seconds()
datetime.datetime.fromtimestamp(st+time)
But any other way of doing this will be welcome!
You could try this:
from datetime import datetime, timedelta
t0 = datetime(1981, 1, 1)
seconds = 1000000
dt = t0 + timedelta(seconds=seconds)
print dt
# 1981-01-12 13:46:40
Here t0 is set to a datetime object representing the "epoch" of 1981-01-01. This is your reference datetime to which you can add a timedelta object initialised with an arbitrary number of seconds. The result is a datetime object representing the required date time.
N.B. this assumes UTC time

Categories