Reputation: 29
First part: I have a Python script that opens a file, gets a starting timecode string in the format:
136:17:30:00 (DOY:HH:MM:SS)
And a stopping timecode string in the format:
137:01:30:00 (DOY:HH:MM:SS)
The user enters the start year (2017), and the stopyear (2017).
I would like to know how to convert the starting and stopping timecode (along with the year string) into a 'datetime" object. This is considered to be an experiment start and stop time.
Second part: The user will enter a "recording" start time and a "recording" stop time in the formats:
2017:136:18:00:00 (YEAR:DOY:HH:MM:SS) 2017:137:01:00:00 (YEAR:DOY:HH:MM:SS)
This is considered to be record start/stop times.
I'd like to convert into a datetime object as well. I suppose it will be the same mechanism as the first part.
I want to first validate that the record stop/start times are within the experiment stop/start times, and be able to subtract stop time from start time.
Some of the Python documentation is confusing to me as to how to do this. Any ideas? Thanks in advance.
Upvotes: 0
Views: 72
Reputation: 322
I don't know what exactly you want from your question. What you are doing with year. I hope the following will help you however:
time1='136:17:30:00'
time2='137:01:30:00'
#yr=2017
from datetime import timedelta
def objMaker(time):
arr=time1.split(':')
obj=timedelta(hours=int(arr[1]),minutes=int(arr[2]),seconds=int(arr[3]))
return obj
obj1=objMaker(time1)
obj2=objMaker(time2)
Upvotes: 0
Reputation: 46789
Python's datetime.strptime()
is used for converting string representations of dates into datatime
objects. It lets you specify %j
for the day of the year as follows:
from datetime import datetime
print datetime.strptime("136:17:30:00", "%j:%H:%M:%S").replace(year=2017)
print datetime.strptime("2017:136:17:30:00", "%Y:%j:%H:%M:%S")
This would display:
2017-05-16 17:30:00
2017-05-16 17:30:00
.replace()
is used to give the datetime
object a year, otherwise it would default to 1900
.
In summary:
%j
- Day of the year as a zero-padded decimal number.
%Y
- Year with century as a decimal number.
%H
- Hour (24-hour clock) as a zero-padded decimal number.
%M
- Minute as a zero-padded decimal number.
%S
- Second as a zero-padded decimal number.
If you convert your start and end codes into datetime
objects, you can then subtract them to give you the time between as follows:
dt_start = datetime.strptime("136:17:30:00", "%j:%H:%M:%S")
dt_end = datetime.strptime("137:01:30:00", "%j:%H:%M:%S")
print dt_end - dt_start
Giving you:
8:00:00
Upvotes: 2