Add duration to time in python - python

I have two strings:
current_time : 4:46:00 PM
duration : 03:20:00
current_time is : %I:%M:%S %p
duration is hour:minute:seconds format.
I have to add the duration in the time .
In the above case : I need to get the output as : 08:06:00 PM
The code that I have tried is :
parsedtime = time.strptime(current_time,"%I:%M:%S %p")
parsedduration = time.strptime(duration,"%I:%M:%S")
parsedtime + datetime.timedelta(parsedduration.tm_hour,parsedduration.tm_min,parsedduration.tm_sec)
print parsedtime
The above is obviously incorrect and not working , please suggest the optimal way.

Your problem is mixing time and datetime objects and not naming your keyword arguments in timedelta.
from datetime import datetime, timedelta
current_time = "4:46:00 PM"
duration = "3:20:00"
parsed_time = datetime.strptime(current_time, "%I:%M:%S %p")
parsed_duration = datetime.strptime(duration, "%I:%M:%S")
then = parsed_time + timedelta(hours=parsed_duration.hour,
minutes=parsed_duration.minute,
seconds=parsed_duration.second)
result = then.strftime("%I:%M:%S %p")
# 08:06:00 PM

import datetime
today1= datetime.date.today()
difference= datetime.timedelta(1)
yesterday= today1 - difference
print (yesterday)
It will give you a point, for example this one finds today-1day. It means yesterday.
time1= time.localtime()
hour1=time1.tm_hour
min1=tim1.tm_min
#do your codes#
So you can define hour and min as a variable and do math.

Related

How to change the date of time instance using python?

I have start_time variable that stores a time string.
start_time = '2022-12-21 22:00:00'
Now Using python i want to change the date of start time to
start_time = '2022-12-28 22:00:00'
I have done this with very ugly approach. Please tell me easy and best way to do that.
I tried with following code.
#its not string its time instance
replacing_date = 2022-12-28 00:00:00
#converting time into string
replacing_date = datetime.strptime(replacing_date,'%Y-%m-%d %H:%M:%S')
replacing_date =replacing_date.split(" ")
start_time = start_time.split(" ")
start_time = datetime.strptime(replacing_date[0]+start_time[1],'%Y-%m-%d %H:%M:%S')
Basically i have to change date on many places. It doesn't seems to be good thing in that case. and it can break if time string format changes.
it can also break if the years or month changes. for example date change to.
start_time = '2023-01-01 22:00:00'
You can use datetime.replace(..):
from datetime import datetime
start_time = "2022-12-21 22:00:00"
new_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S").replace(day=28)
print(new_time)
Output:
2022-12-28 22:00:00
Or regexp:
import re
new_time = re.sub(r"\d{4}-\d{2}-\d{2}", "2022-12-28", "2022-12-21 22:00:00", 0)
print(new_time)
Output:
2022-12-28 22:00:00
from datetime import datetime, timedelta
start_time = '2022-12-21 22:00:00'
replacing_date = datetime.strptime(start_time,'%Y-%m-%d %H:%M:%S')
new_time = replacing_date+timedelta(days=7)
print(new_time)
Output:
2022-12-28 22:00:00
use timedelta to change time.

Get GMT timestamp in python

I need to get GMT timestamps, a timestamp when start a day, and another when end a day, the following example is for today (2022-03-29):
Start of Day (Unix Timestamp): 1648512000
End of Day (Unix Timestamp): 1648598399
you can check this in https://www.epochconvert.com/
and my code only for the case of start of day is the next one :
from datetime import datetime
start_date = datetime.today().strftime('%Y-%m-%d')
start_date += ' 00:00:00'
print(start_date)
timestamp = time.mktime(datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S").timetuple())
print(timestamp)
and my output:
2022-03-29 00:00:00
1648533600.0
as you can see it's not the answer I'm waiting for, that timestamp is for my Local Time but i need a GMT timestamp as answer (1648512000 in this case)
How could i do it ?
Thanks in Advance!!
if you want to derive Unix time from datetime objects, make sure to set time zone / have aware datetime:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
print(now)
# 2022-03-29 23:34:51.701712+00:00
now_floored = datetime.combine(now.date(), now.time().min).replace(tzinfo=timezone.utc)
print(now_floored)
# 2022-03-29 00:00:00+00:00
now_floored_unix = now_floored.timestamp()
print(now_floored_unix)
# 1648512000.0
If you do not do that (have naive datetime), Python will use local time:
now = datetime.now()
now_floored = datetime.combine(now.date(), now.time().min)
print(now_floored.astimezone())
# 2022-03-29 00:00:00-06:00 # <- my current UTC offset is -6 hours
print(now_floored.timestamp(), (now_floored_unix-now_floored.timestamp())//3600)
# 1648533600.0 -6.0

Diff between time string and current time without year

I want to determine the difference between a date string and the current time.
The problem is that the time string does not contain a year (But the current datetime does, so that would be make trouble on year change?)
Here's my current code:
date_parsed = datetime.strptime('Fri Apr 27 19:09:53', '%a %b %d %H:%M:%S')
current_time = datetime.now()
We can assume that date_parsed occurred during the last 365 days, right?
In that case, use .replace() to change the year of that date, compare it to the current date, and adapt the year according to the result of that comparison: if the date is after now, then the parsed date should be adapted, otherwhise, it's ok:
from datetime import datetime
current_time = datetime.now()
date_parsed = datetime.strptime('Fri Apr 27 14:09:53', '%a %b %d %H:%M:%S').replace(year=current_time.year)
if date_parsed > current_time:
date_parsed = date_parsed.replace(year=current_time.year - 1)
print(date_parsed, current_time, current_time - date_parsed)
E.g. with a date in "the past":
2018-04-27 14:09:53 2018-04-27 18:28:10.484371 4:18:17.484371
E.g. with a date in the "future":
2017-04-30 14:09:53 2018-04-27 18:30:48.864598 362 days, 4:20:55.864598
You could do it with total_seconds and modulo arithmetic, but then I think you have issues with things like leap years. Probably the best way is to try two replacements:
tdiff = current_time - date_parsed.replace(year=current_time.year)
if tdiff.days < 0:
tdiff = current_time - date_parsed.replace(year=current_time.year-1)
You can use .strftime() method to synchronize your string time and current time as following:
from datetime import datetime
date_parsed = datetime.strptime('Fri Apr 27 19:09:53', '%a %b %d %H:%M:%S')
current_time = datetime.now().strftime("%m-%d %H:%M:%S")
date_ = date_parsed.strftime("%m-%d %H:%M:%S")

Subtract hours and minutes from time

In my task what I need to do is to subtract some hours and minutes like (0:20,1:10...any value) from time (2:34 PM) and on the output side I need to display the time after subtraction.
time and hh:mm value are hardcoded
Ex:
my_time = 1:05 AM
duration = 0:50
so output should be 12:15 PM
Output should be exact and in AM/PM Format and Applicable for all values
(0:00 < Duration > 6:00) .
I don't care about seconds, I only need the hours and minutes.
from datetime import datetime, timedelta
d = datetime.today() - timedelta(hours=0, minutes=50)
d.strftime('%H:%M %p')
This worked for me :
from datetime import datetime
s1 = '10:04:00'
s2 = '11:03:11' # for example
format = '%H:%M:%S'
time = datetime.strptime(s2, format) - datetime.strptime(s1, format)
print time
from datetime import datetime
d1 = datetime.strptime("01:05:00.000", "%H:%M:%S.%f")
d2 = datetime.strptime("00:50:00.000", "%H:%M:%S.%f")
print (d1-d2)

How do I find the difference between two times in python in a format?

I was wondering how can I calculate the time difference between two times which have PM and AM next to them for example. I have 12:16:44 pm and 01:01:45 pm but when I use this code:
from datetime import datetime
from datetime import timedelta
s1=12:16:44
s2=01:01:45
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2), FMT) - datetime.strptime(s1), FMT)
if tdelta.days < 0:
tdelta = timedelta(days=0,
seconds=tdelta.seconds,
microseconds=tdelta.microseconds)
but this is the output I get
12:16:44 | 01:01:45 | Time Difference: -1 day, 12:45:01 but they are both PM values? Thanks
In Python, %H means 24 hour time format. %I is 12 hour format and even then you should specify PM in the string
Try that (and fix syntax errors):
s1='12:16:44 PM'
s2='01:01:45 PM'
FMT = '%I:%M:%S %p'

Categories