Convert two timestamps to time elapses in Python - python

I'm trying to get the time elapsed between two string timestamps in my Python code.
Example:
Time Started: "2022-01-07 14:30"
Time Ended: "2022-01-07 15:45"
I want the answer to return as an int in number of minutes.
So, in this example it would be 75 since that is the number of minutes elapsed between the starting and ending timestamps.

You don't appear to have tried anything. Start with this:
Call datetime.strptime() to convert to datetime objects
Subtract the objects to get a timedelta
Divide timedelta.total_seconds() by sixty to get the number of minutes

from datetime import datetime
class Convert:
def main(start,end):
dt1=datetime.strptime(start, '%Y-%d-%m %H:%M')
dt2=datetime.strptime(end, '%Y-%d-%m %H:%M')
time1=str(dt1.time()).split(":")
time2=str(dt2.time()).split(":")
for i in range(0,len(time1)):
time1[i]=int(time1[i])
for j in range(0,len(time2)):
time2[j]=int(time2[j])
print(time1)
hour_to_min1=time1[0]*60+time1[1]+time1[2]
hour_to_min2=time2[0]*60+time2[1]+time2[2]
print(hour_to_min1)
print(hour_to_min2)
total_time_taken=hour_to_min2-hour_to_min1
print(f"The total time taken is {total_time_taken} minutes")
start=str(input("Enter datetime in the format yyyy-mm-dd hh:mm:ss"))
end=str(input("Enter datetime in the format yyyy-mm-dd hh:mm:ss"))
(Convert.main(start,end))
This was too simple....:)

Related

strptime() error - Time from sensor with more than 24 hours (e.g. 24:01:53)

I am using datetime.strptime() to convert a string containing time and date from a sensor into a datetime object.
The code sometimes fails. Minimal example:
datetime.strptime('1/9/2021 24:01:53', '%d/%m/%Y %H:%M:%S')
Output error:
ValueError: time data '1/9/2021 24:01:53' does not match format '%d/%m/%Y %H:%M:%S'
I am guessing this has to do with the fact that the time is more than 23:59:59 - which seems to me a non-realistic time (I would think that 1/9/2021 24:01:53 could potentially be 2/9/2021 00:01:53 - a time format which I have never seen).
Is this a non-standard way of representing time or possibly a hardware/software issue with the sensor acquisition system? If it is a different way of representing time, how can I convert it to a standard datetime object?
Kind regards,
D.F.
If the hour exceeds 23 in a variable representing time, a good option is to create a timedelta from it, which you can then add to a datetime object. For given example that might look like
from datetime import datetime, timedelta
def custom_todatetime(s):
"""
split date/time string formatted as 'DD/MM/YYYY hh:mm:ss' into date and time parts.
parse date part to datetime and add time part as timedelta.
"""
parts = s.split(' ')
seconds = sum(int(x) * 60 ** i for i, x in enumerate(reversed(parts[1].split(':'))))
return datetime.strptime(parts[0], "%d/%m/%Y") + timedelta(seconds=seconds)
s = '1/9/2021 24:01:53'
print(custom_todatetime(s))
# 2021-09-02 00:01:53
Note: conversion of hh:mm:ss to seconds taken from here - give a +1 there if helpful.

How to parse and calculate the elapsed seconds in a date stamp with this format?

Given a string like this:
2020-04-09T13:15:52.838Z - 2020-04-09T13:16:09.704Z
What is the correct way to calculate the amount of elapsed seconds? So far I tried this:
s = '2021-03-09T13:15:52.838Z - 2021-03-09T13:16:09.704Z'.split(' - ')
datetime.strptime(s[0], "%Y-%m-%d").date() - datetime.strptime(s[1],"%Y-%m-%d").date()
However, I am not sure how to extract the seconds and calculate the elapsed time between the two time stamps. Any idea of how to get the elapsed time in seconds?
Basically, you want to convert each string into a datetime (here using datetime.strptime() and using a format string that matches the format of your time strings) and then subtract one from the other to get a datetime.timedelta object. Then you can call the total_seconds() method on the timedelta object. Here's one way you might do it:
import datetime
s = '2021-03-09T13:15:52.838Z - 2021-03-09T13:16:09.704Z'.split(' - ')
first_time = datetime.datetime.strptime(s[0], '%Y-%m-%dT%H:%M:%S.%fZ')
second_time = datetime.datetime.strptime(s[1], '%Y-%m-%dT%H:%M:%S.%fZ')
time_delta = second_time - first_time
print(time_delta.total_seconds())

Converting Epoch time format to standard time format

I am having an issue with converting the Epoch time format 1585542406929 into the 2020-09-14 Hours Minutes Seconds format.
I tried running this, but it gives me an error
from datetime import datetime
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
datetime.utcfromtimestamp(df2.timestamp_ms).strftime('%Y-%m-%d %H:%M:%S')
error : cannot convert the series to <class 'int'>
What am I not understanding about this datetime function? Is there a better function that I should be using?
edit: should mention that timestamp_ms is my column from my dataframe called df.
Thanks to #chepner for helping me understand the format that this is in.
A quick solution is the following:
# make a new column with Unix time as #ForceBru mentioned
start_date = '1970-01-01'
df3['helper'] = pd.to_datetime(start_date)
# convert your column of JSON dates / numbers to days
df3['timestamp_ms'] = df3['timestamp_ms'].apply(lambda x: (((x/1000)/60)/60/24))
# add a day adder column
df3['time_added'] = pd.to_timedelta(df3['timestamp_ms'],'d')
# add the two columns together
df3['actual_time'] = df3['helper'] + df3['time_added']
Note that you might have to subtract some time off from the actual time stamp. For instance, I had sent my message at 10: 40 am today when it is central time (mid west USA), but the timestamp was putting it at 3:40 pm today.

Python how to get current time as an integer

This is my code that I tried to use but it doesn't work since it's a string
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M")
print("time=", current_time)
wake_up=0
x=current_time - wake_up - 0.40
wake_up = float(input("when are you gonna wake up"))
print(x)
I am trying to make a calculator where as it prints the current time. (for example 23:00) and then the input asks what time are you going to wake up and you write (for example 08:30) and the output should be "You will get 09:30 hours and minutes of sleep" or preferably "You will get 9 hours and 30 minutes of sleep"
I tried to do this but it is a string and cannot be calculated and I tried to find an integer version of the now.strftime module. Can someone help me find out how to do this?
You'll need to use datetime.strptime(), which takes in a date string and a format string (reference here) and converts the string to a datetime object.
In your case, you would use the following to convert wake_up to a datetime object:
dt = datetime.strptime(wake_up, "%H:%M")
Modifications done based on your code:
from datetime import datetime, date
now_time = datetime.now().time() # get time only
current_time_str = now.strftime("%H:%M")
print("time=", current_time_str)
#wake_up = input("when are you gonna wake up")
wake_up = '08:30' # assuming this is user input
wake_up_time = datetime.strptime(wake_up, "%H:%M").time()
x = datetime.combine(date.today(), wake_up_time) - datetime.combine(date.today(), now_time)
print(str(x)) #also, you can get hours by x.seconds/3600
Other questions will help you.
Python speed testing - Time Difference - milliseconds
Converting string into datetime
subtract two times in python
Format timedelta to string

How to convert milliseconds to date and time format?

I have a value in milliseconds in a Python program. For example: 1557975599999
And I would like to convert it to a string with days and hours, minutes, seconds. How can I do this?
To convert unix timestamp to datetime, you can use datetime.fromtimestamp(). The only problem, that your timestamp is in miliseconds, but function expect timestamp in seconds. To cut miliseconds you can divide timestamp to 1000.
Code:
from datetime import datetime
a = 1557975599999
date = datetime.fromtimestamp(a // 1000)
print(date)
Output:
2019-05-16 05:59:59
Upd.
#Daniel in comments noticed that fromtimestamp() accept floats, so we can save miliseconds from original timestamp. All we need is just to remove one symbol :D
date = datetime.fromtimestamp(a / 1000)
With Pandas’ to_datetime()
import pandas as pd
pd.to_datetime(a, unit='ms')
# Or with a dataframe(column):
df['date'] = pd.to_datetime(df['Millisecond_time'], unit='ms')

Categories