As I need to transform the time format hh:mm to the count of minutes. Doing the maths would be:
hh*60+mm
I came across with the method mktime, which I thought it was to get the EPOCH time in minutes of a given datetimeobject. In this way I convert from datetimeto integer.
I wrote this in order to calculate the time of the day in minutes:
(the outputs in the boxes below)
a = datetime.now()
print type(a)
print a
b= '2017-07-05 00:00:00.0'
b = datetime.strptime(b, "%Y-%m-%d %H:%M:%S.%f")
type(b)
out: type 'datetime.datetime'
out: type 'datetime.datetime'
As both objects are datetime I used the method mktime that I found searching for a way to transform from timestamp to integer
timestamp = int(time.mktime(a.timetuple()))-int(time.mktime(b.timetuple()))
type(timestamp)
print timestamp
print a
print b
And the output is:
out: 62189
out: 2017-07-05 17:16:29.134026
out: 2017-07-05 00:00:00
So the value 62189is seconds? Am I using EPOCH time?
(sorry if the question is bit fool, I am quite beginner, that's why I need help)
Thanks!
I would come with a solution like:
import time
t = time.strptime("02:24", "%H:%M") # Replace "02:24" with your string parameter
nb_minutes = t.tm_hour * 60 + t.tm_min
This transforms the time format "hh:mm" to the count of minutes as requested in your OP.
Note that there is a distrinction between a date, a datetime and a time. Python offers more flexibility than Javascript Date() on this.
Basically:
date = YYYY-MM-DD
time = HH:MM:ss
datetime = YYYY-MM-DD HH:MM:ss
Depending of your calculations, using the correct object in the python library will save you efforts all while making your source code more semantically readable.
Related
so i am taking the difference between two times (2022-07-20 23:10:00.990000) and 2022-07-20 23:10:02.100000. that gives me back 0:00:01.110000. i want that to transform to HH:MM:SS without the microseconds. the easiest way to take off microseconds is to do "avg_inqueue_time = str(avg_inqueue_time).split(".")[0]" that will give me 0:00:01. then i try to do avg_inqueue_time_transformed = datetime.strptime('%H:%M:%S', avg_inqueue_time) but gives an error ValueError: time data '%H:%M:%S' does not match format '0:02:07'.
any ideas how to transform that?
I believe a fast approach is to take a different time delta object where you only pick the seconds.
import datetime
time_1 = datetime.datetime(2022,7,20,23,10,00,990000)
time_2 = datetime.datetime(2022,7,20,23,10,2,100000)
timediff=(time_2-time_1)
timediff_wo_microseconds = datetime.timedelta(days=timediff.days, seconds=timediff.seconds)
print(timediff_wo_microseconds)
I get the departure variable by asking for it as input into a string. Using this code as shortened version to show where it starts.
departure = "2022-11-12 14:30"
datetime_object = datetime.strptime(departure, "%Y-%m-%d %H:%M")
current_time = datetime.utcnow()
print(datetime_object-timedelta(current_time))
I am trying to subtract this and basically receive any sort of outcome in days + mins +seconds or in just one variable like minutes. i.e.
>>>
10000 mins
What I am currently getting is this
>>>
print(datetime_object-timedelta(current_time))
TypeError: unsupported type for timedelta days component: datetime.datetime
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.
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.
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