Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Time math
-
I'm getting lost in the timedelta, datetime documents. I can't quite figure out how to add and subtract times. My current personal project is creating a simple time tracker for work. I want to punch in and punch out. The program will calculate the time and total it up. I write the current time to my set up dictionary using strftime("%H"), M, & S. I read it and write it with json and save it to a txt. Maybe my issue is that I split up the components? I have everything in place except the grasp of datetime documents. Any help is greatly appreciated.
-
As a general advice, I'd recommend saving absolute timestamps instead of hours and minutes (which can be calculated from the timestamp later). With your approach, the calculations will be wrong if you cross midnight...
-
import datetime time_file_name = 'time_storage.txt' datetime_fmt = '%Y-%m-%d %H:%M:%S.%f' def write_datetime(in_datetime, file_name = time_file_name): with open(file_name, 'w') as out_file: out_file.write(in_datetime.strftime(datetime_fmt)) def read_datetime(file_name = time_file_name): with open(file_name) as in_file: return datetime.datetime.strptime(in_file.readline().strip(), datetime_fmt) def elapsed_datetime(start_datetime, end_datetime = datetime.datetime.now()): return end_datetime - start_datetime # returns a datetime.timedelta start_datetime = datetime.datetime(2014, 1, 1) # or datetime.datetime.now() write_datetime(start_datetime) new_datetime = read_datetime() print(new_datetime) print(elapsed_datetime(new_datetime)) print(elapsed_datetime(start_datetime))
-
omz, thank you for the advice. At what point do I start paying you ccc?! Seriously. You should offer classes, I'd take them. I appreciate the fruits of your efforts. Apparently I was taking the long way around...
-
ccc is an excellent coder to have as part of the community :)