How to calculate parts of a timestamp - python-3.x

I have a problem with my code. I have to datetime values as a string. I want to calculate the
time passed between them. I can archive this with the following code:
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
tstamp1 = datetime.strptime('2021-02-20 12:25:08', fmt)
tstamp2 = datetime.strptime('2021-02-20 11:19:17', fmt)
td = tstamp1 - tstamp2
The result I get is 1:05:51.
Now I have another value as string: 00:58:08
Here I also want to know how many time passed between them:
1:05:51 - 00:58:08.
I need the result formated like this: 00:07:43
I really dont know how to do this. Can somebody help me?

This should help your requirement.
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
tstamp1 = datetime.strptime('2021-02-20 12:25:08', fmt)
tstamp2 = datetime.strptime('2021-02-20 11:19:17', fmt)
td = tstamp1 - tstamp2
tr = '00:58:08'
tr = datetime.strptime(str(tr), '%H:%M:%S')
td = datetime.strptime(str(td), '%H:%M:%S')
ans = td - tr
print(ans)

Related

Dealing with trailing decimals at the end of a DateTime

I am trying to convert the string below into a datetime object using datetime.strptime, and I just can't seem to figure out .746Z at the end.
datetime_str = '2022-04-21T08:17:49.746Z'
datetime_object = datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S.%z')
print(datetime_object)

Change panda date format into another date format?

How do I convert this format below into the result format ?
import pandas as pd
date = pd.date_range('2022-01-01',2022-01-31', freq = 'H')
Result:
'2021-01-01T01%3A00%3A00',
What is the correct name for the result time format ? Have tried using urlilib.parse module, but it did not have T and it can take 1 date.
Thank you !
This so called url encode , so we need urllib, notice here %3A = ':'
import urllib
date.astype(str).map(urllib.parse.quote)
Out[158]:
Index(['2022-01-01%2000%3A00%3A00', '2022-01-01%2001%3A00%3A00',
....

Time cannot be set in the past condition Python

What I need to do.
I need this program to not allow a user to input a date that's in the past. when I try it as it currently is i get the following error message. TypeError: '<' not supported between instances of 'datetime.datetime' and 'str'.
from datetime import datetime
from datetime import date
def addNewItems():
end = 4
while end == 4:
ToDoList = [ ]
Name = input("Enter the name of your task")
dateIn = input("Enter the task completion date. yyyy/mm/dd HH:MM:SS")
date = datetime.strptime(dateIn, "%Y/%m/%d %H:%M:%S")
now = datetime.now()
now_ = now.strftime("%d/%m/%Y %H:%M:%S")
if date < now_:
print("Time entered is in the past! Select options again")
continue
if Name in ToDoList:
print("Task already exists! Select options again")
continue
if date < now_ and Name not in ToDoList:
ToDoList.append(Name, date)
print("Task Added Sucessfully")
break
You actually need two datetime objects to use the < comparison directly.
You just need to compare date with now, intead of date with now_ in order to do what you want.
And just an advice. You're importing date from datetime library, so you should avoid creating variables with the same name if you intend calling the original date somewhere else in your code

date-time-string to UNIX time with milliseconds

I need to convert a date/time string to UNIX timestamp including the milliseconds. As the timetuple() does not include milli or microseconds I made a short workaround. But I was wondering, is there a better/nicer way to do this?
import datetime as dt
import time
timestamp = '2018-01-19 10:00:00.019' # example of input time string
tmp = timestamp.split('.')
millisec = tmp[-1] # extracting only milli-seconds
UX_time = time.mktime(dt.datetime.strptime(tmp[0], '%Y-%m-%d %H:%M:%S').timetuple()) + float(millisec)/1e3
print(UX_time)
1516352400.019
I realize my timezone is off by one hour, so you might be getting
print(UX_time)
1516356000.019
you can try this:
timestamp = '2018-01-19 10:00:00.019'
tmp=np.datetime64(timestamp)
print(tmp.view('<i8')/1e3)
output:
1516352400.019
Also possible with your current code:
import datetime as dt
import time
timestamp = '2018-01-19 10:00:00.019' # example of input time string
ts = dt.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f')
UX_time = time.mktime(ts.timetuple()) + ts.microsecond/1e6
print "%.3f" %UX_time

Convert '0000-00-00' to 'flag' in python

I want to convert some data of dates into the string after checking them in a specific range. I have first converted all data into type float so that it can provide output as dates format but when I applied this for the dates it shows:
a1 = float(a1)
ValueError: could not convert string to float: '0000-00-00'
My whole code is:
import xlrd
import os.path
from datetime import datetime
date_array = []
wb = xlrd.open_workbook(os.path.join('E:\Files','SummaryLease.xlsx'))
sh = wb.sheet_by_index(0)
for i in range(1,sh.nrows):
a1 = sh.cell_value(rowx=i, colx=80)
if a1 is '0000-00-00':
date_array.append('flag')
else:
a1 = float(a1)
a1_as_datetime = datetime(*xlrd.xldate_as_tuple(a1, wb.datemode))
date_array.append(a1_as_datetime.date())
print(date_array)
How should I solve this?
Don't compare strings using is operator, use ==.
if a1 == '0000-00-00':
date_array.append('flag')
else:
a1 = float(a1)
You can read more about the difference here:
Is there a difference between `==` and `is` in Python?

Resources