Python3 Datetime (delta) to Seconds (Including Days) - python-3.x

Hopefully just a simple question. I want to convert a datetime object to seconds and include the days. I've just noticed that my code skipped the day. Please note times are just an example and not 100% accurate.
Content of oldtime.txt (2 days ago):
2021-09-16 19:34:33.569827
Code:
oldtimefile = open('oldtime.txt', 'r+')
oldtme = oldtimefile.read()
datetimeobj = datetime.strptime(oldtme, "%Y-%m-%d %H:%M:%S.%f")
finaltime = datetime.now() - datetimeobj
print(finaltime.seconds)
If I just print finaltime then I get 1 day, 22:13:30.231916.
Now if we take today's date and time - just for argument sake - (2021-09-18 17:34:33.569827) as now then I actually get 80010 seconds instead of roughly 172800 seconds. It's ignoring the day part.
How can I include the day and convert the entire object to seconds?
Thanks.

Instead of .seconds you can use .total_seconds():
from datetime import datetime
oldtme = "2021-09-16 19:34:33.569827"
datetimeobj = datetime.strptime(oldtme, "%Y-%m-%d %H:%M:%S.%f")
finaltime = datetime.now() - datetimeobj
print(finaltime.total_seconds())
Prints:
164254.768354

Related

How to remove milliseconds in datetime python?

I want to print the amount of days, hours, minutes and seconds until christmas day but when it prints, it also gives me the millisecond. I tried doing print(remain_until_xmas.strip(.) but that didn't work. Here is the code
import datetime as dt
xmas = dt.datetime(2020, 12, 25)
now = dt.datetime.now()
until_xmas = xmas - now
print(until_xmas)
To get the time live, you can use this code:
import time
time = str(time.strftime("%M")) + ":" + str(time.strftime("%S"))
print(time)
This will give you the current time in Minutes and Seconds, and if you put it in a loop, it will keep updating itself.
If you want the day and month, you can use
print(time.strftime("%A, %B %e")) -
With this code, you can then subtract the Xmas date from the current date, and retrieve what you want.
This would be your final code:
import time
month = time.strftime("%m")
day = time.strftime("%d")
hour = time.strftime("%H")
minute = time.strftime("%M")
second = time.strftime("%S")
chrmonth = 12
chrday = 23
chrhour = 12
chrminute = 60
chrsecond = 60
print("The time until christmas is, ", int(chrmonth) - int(month), "months", int(chrday) - int(day), "days", int(chrhour) - int(hour), "hours", int(chrminute) - int(minute), "minutes", int(chrsecond) - int(second), "seconds")
Hopefully this helps!
you can use .strftime()
print(until_xmas.strftime("%m/%d/%Y, %H:%M:%S"))
see more here about strftime.

tz.localize() returning incorrect offset

I have the following function (with exaggerated logger statements just to help with debugging right now) that takes an input timezone and datetime, and converts it to PST:
def convert_to_pst_equivalent_time(input_datetime, input_timezone):
timezone = pytz.timezone(input_timezone)
dt_date = input_datetime.split("T")[0]
dt_time = input_datetime.split("T")[1].split("-")[0] if "-" in input_datetime.split("T")[1] else \
input_datetime.split("T")[1].split("+")[0]
dt = datetime.strptime((dt_date + " " + dt_time), "%Y-%m-%d %H:%M:%S")
logger.info("DT is: {}".format(dt))
dt = timezone.localize(dt)
logger.info("DT is now: {}".format(dt))
dt = dt.astimezone(pytz.timezone("America/Los_Angeles"))
logger.info("DT is finally: {}".format(dt))
return dt.strftime("%Y-%m-%dT%H:%M:%S")
If we have some inputs like "2020-02-03T00:00:00" as "input_datetime" and "Pacific/Norwalk" as the input_timezone, my outputs are the following:
DT is: 2020-02-03 00:00:00
DT is now: 2020-02-03 00:00:00+12:00
DT is finally: 2020-02-02 04:00:00-08:00
However, based on this website (https://www.zeitverschiebung.net/en/difference/timezone/pacific--norfolk/city/5368361), Pacific/Norwalk should be +11:00, not +12:00, and therefore, my final output after converting to Los Angeles time is also off by 1 hour. Strangely, this is working for other timezones, but this one in particular is offering problems. I've tried doing things like replacing tzinfo= and localize() (as seen above) but neither appear to be returning the right offset. Any ideas?

Date Time difference between hour of the day and time now

Time = datetime.datetime.now().time()
I wanted to find the difference in seconds between the Time above^ and the hour of the day:
for example if the Time = 15:07:25.097519, so the hour of the day is 15:00:00, i want to store 445.097519‬ seconds to a variable.
How can I do that?
I am an amateur at this please help!!
import datetime
now = datetime.datetime.now()
hour = now.replace(minute=0, second=0, microsecond=0)
seconds = (now - hour).seconds + (now - hour).microseconds / 1000000
Here is one way to do it. Extract the hour from current time, and initialize a new datetime.time object with hour as input. Then you convert both of the timestamps to datetime and then do the subtraction. Code below does that
Time = datetime.datetime.now().time()
hour = str(Time).split(":")[0]
currentHourTime = datetime.datetime(2019,10,31,int(hour),0,0,0).time()
dateTimeCurr = datetime.datetime.combine(datetime.date.today(), Time)
dateTimeCurrHour = datetime.datetime.combine(datetime.date.today(), currentHourTime)
dateTimeDifference = dateTimeCurr - dateTimeCurrHour
dateTimeDifferenceInSeconds = dateTimeDifference.total_seconds()
print(dateTimeDifferenceInSeconds)

Number of samples, -5, must be non-negative using panda python

I have a csv file with date and time. I want to give specific timeinterval (60min) in between time range (start time and end time). I wrote a code with a date. But it gives me an error Number of samples, -5, must be non-negative. Then I checked with separate csv file with less data. Then I found that I have time like 9:53 , 10:20 ,11:42 .... Then when I'm dividing to find num_periods then its give me an error.
example
take date range like
2018 /8/6 start time is 6:00
2018/8/6 end time is 23:52
then it between I have time like 7:00, 8:52,10:42 so on.
after that in next day I have a time period like this.
So when I tried to find a num_periods then it give me this error.
I want to specify time in between this time_range
(start_time+time_interval(3600 in seconds (60min)) in between time_range)
Can anyone give me solution for this?
my code is,
time_interval = 3600
date_array = []
date_array.append(pd.to_datetime(data['date'][0]).date())
start_time = []
end_time = []
temp_date = pd.to_datetime(data['date'][0]).date()
start_time.append(pd.to_datetime(data['time'][0], format='%H:%M:%S').time())
for i in range(len(data['date'])):
cur_date = pd.to_datetime(data['date'][i]).date()
if( cur_date > temp_date):
end_time.append(pd.to_datetime(data['time'][i-1], format='%H:%M:%S').time())
start_time.append(pd.to_datetime(data['time'][i], format='%H:%M:%S').time())
date_array.append(cur_date)
temp_date = cur_date
end_time.append(pd.to_datetime(data['time'][len(data['date'])-1], format='%H:%M:%S').time())
datetime_array = []
for i in range(len(date_array)):
s_time = datetime.datetime.combine(date_array[i],start_time[i])
e_time = datetime.datetime.combine(date_array[i], end_time[i])
timediff = (e_time - s_time)
num_periods = int(timediff.total_seconds()/time_interval) +1
time_list = pd.date_range(start=s_time, end = e_time, periods=num_periods ).to_pydatetime()
datetime_array.extend(time_list)
error:
subset of my csv file
It looks like num_periods is negative:
num_periods = int(timediff.total_seconds()/time_interval) + 1
the easiest solution is to take the abs value instead:
num_periods = abs(int(timediff.total_seconds()/time_interval)) + 1
Note: that date_range supports ranges in reverse order (where start > end).

Average speed based on time and distance - Python

I'm tryng to figure out how I can fix my problem here, but it keeps failing.
So I currently have this code:
#staticmethod
def avg_speed():
# Speed = Distance ÷ Time
cur_time = datetime.datetime.now().replace(microsecond=0)
db_time_record = DB().start_time()
time_diff = cur_time - db_time_record
# print(str(time_diff).split(":"))
total_distance = DB().get_total_distance()
result = (total_distance / (float(time_diff.total_seconds()))) * 60
return round(result, 2)
But the thing is, the average speed is so high, it is not possible that the speed is correct.... Now, what the DB() record has a MySQL DATETIME object.
That looks like: datetime.now().strftime("%Y-%m-%d %H:%M:%S") (2017-08-22 15:28:19)
Now what I want, as stated in the code, is the average speed based on the distance traveled and the time. The distance is in meters and the time should be in seconds?
What am I doing wrong here?
I don't have a MySQL database available to test your code, but if you can read the start_time from the DB as a string in the format like "2017-08-22 15:28:19" then the following example shows how to do a speed calculation:
import datetime
# (simulate reading time from database as string)
time_string_from_db = "2017-08-22 15:28:19"
dbtime = datetime.datetime.strptime(time_string_from_db, "%Y-%m-%d %H:%M:%S")
cur_time = datetime.datetime.now().replace(microsecond=0)
print ("dbtime: " + repr(dbtime))
print ("cur_time: " + repr(cur_time))
elapsed = cur_time - dbtime
seconds = elapsed.total_seconds()
print ("elapsed: " + repr(elapsed))
print ("seconds: " + repr(seconds))
distance = 500
speed = distance / seconds
print ("speed: " + repr(speed))
Hope some of this may be useful.

Resources