Find date upon which defined age in seconds is reached - python-3.x

I am attempting to write a program that
takes a certain number of seconds (say 1000000000), then
takes a given date (for example one's birthday) and
then determines when (at which given date) this age in number of seconds has been reached.
Certainly, the program should recognize if that age in number of seconds is in the past.
But even before building a check for this, the code runs into problems.
After receiving error message I tried changing parameter name from month to umonth in the input stage. That brought no difference.
from datetime import datetime
seconds = int(input("seconds: "))
year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))
#Calculate time in seconds between now and the day of birth
date = (datetime(year=year, month=month, day=day) - datetime(seconds)).total_seconds()
print("You will be {} seconds old on {} old.".format(seconds, date))
I am still dabbling with the datetime library.
I received a TypeError from python3.
"TypeError: Required argument 'month' (pos 2) not found"
Edit:
Following suggestions in the comments, I modified the code for using a new method, to convert a date into seconds.
from datetime import datetime
#seconds = int(input("seconds: "))
seconds = 1000000000
#year = int(input("year: "))
#month = int(input("month: "))
#day = int(input("day: "))
year = 1987
month = 9
day = 11
date = datetime.datetime(year,month,day)
#Calculate time in seconds between now and the day of birth
(date.total_seconds(datetime(year=year, month=month, day=day)) - seconds)
print("You will be {} seconds old on {} old.".format(seconds, date))
That yields an AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
I am aware I dont know exactly how to use datetime library.
Working through the docs to understand.
But still, those things seem trivial to achieve.
Perhaps someone can explain.
The goal is, as before, to take a number of seconds and a date of birth.
And to see when, from the date of birth on, the number of seconds will be reached.

AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
You are receiving the above error because you already used import datetime. No need of writing datetime.datetime. You can directly use datetime(year, month, day).

Related

Why is my python time comparison wrong every minute?

Hello everyone Im making a time comparison project.
Basically what Im trying to do is have my code take a reading of time and then take a separate reading of time, if the system where to go to sleep for any length of time, the code will see that a time difference has occurred.
The problem that Im running into is if statement will trigger every minute with a value of 40 seconds plus the 1 second delay I added and I don't know why.
Any thoughts?
import datetime
import time
while True:
current_time_A = datetime.datetime.now()
print("current time A ",
int(current_time_A.strftime("%H%M%S")))
time.sleep(1)
current_time_B = datetime.datetime.now()
print("current time B ",
int(current_time_B.strftime("%H%M%S")))
time_elapsed = ((int(current_time_B.strftime("%H%M%S"))) - (int(current_time_A.strftime("%H%M%S"))))
print("time_elapsed = ",time_elapsed)
if time_elapsed >= 5:
print("time changed more then 5 seconds")
Here's the output you will get
current time A 1959
current time B 2000
time_elapsed = 41
time changed more then 5 seconds
current time A 2000
current time B 2001
1
current time A 2001
So the problem you're facing is due to how you're setting everything up. Basically, you're getting the 2 times' hour, minute, and second as a string, converting them to an int, and then subtracting their differences. Seconds only go up to 59 before going back to 00. So, when current_time_A's second is 59 and current_time_B's second is 00, the difference comes out to be 41 (because the minute changes as well).
Instead of converting back and forth between types (datetime.datetime -> str -> int), I suggest using time.time() to get the timestamp and do your calculations on that:
import time
while True:
current_time_A = time.time()
print(f"Current time A {current_time_A}")
time.sleep(1)
current_time_B = time.time()
print(f"Current time B: {current_time_B}")
# calculate how many seconds have elapsed since the start of the program
elapsed_time = current_time_B - current_time_A
print(f"Elapsed time: {elapsed_time}")
# round to the nearest second
print("Elapsed time (rounded):", round(elapsed_time))

Duration Calculator in Python

I have been studying Python by myself since a month ago.
I want to make a duration calculator that shows the total time of each different duration.
For instance, there are two different flights I have to take, and I want to get the total time I would be in the airplanes. It goes like this.
a = input('Enter the duration: ') #11h40m
b = input('Enter the duration: ') #13h54m
#it may show the total duration
01d01h34m
Try this :
Edit : I tried to use strftime to format the 'duration' but had some issues with day.
So I did it manually (you can format it the way you wish)
import datetime
import time
# Convert str to strptime
a_time = datetime.datetime.strptime("11h40m", "%Hh%Mm")
b_time = datetime.datetime.strptime("13h54m", "%Hh%Mm")
# Convert to timedelta
a_delta = datetime.timedelta(hours = a_time.hour,minutes=a_time.minute)
b_delta = datetime.timedelta(hours = b_time.hour,minutes=b_time.minute)
duration = (a_delta + b_delta)
print(str(duration.days) + time.strftime('d%Hh%Mm', time.gmtime(duration.seconds)))
'1d01h34m'

Can I get timedelta(days=180) from datetime.today().strftime('%Y%m%d') in python3?

I'm writing a script that moves files whose names begin with YYYYMMDD (example 20180201, 20180203) to an archive directory if they are older than 180 days. This script will run every day from a cron job.
So datetime.today().strftime('%Y%m%d') returns a string, obviously. I can't seem to find a way to have datetime return in an int.
I could do this:
toDay = int(datetime.today().strftime('%Y%m%d'))
but somehow that seems kludgey.
I can't figure out what kind of object datetime.timedelta(days=180) produces.
It produces a timedelta object. You can add and subtract timedelta objects with objects like datetime objects to produce new objects with the time changed by that amount.
from datetime import datetime, timedelta
def get_date_from_filename(filename):
return datetime.strptime(filename[:8], "%Y%m%d")
filename = "20180201file.txt"
today= datetime.today()
if get_date_from_filename(filename) + timedelta(days=180) <= today:
print("File is 180 days old")
else:
print("file is not that old")

Count down to a week later from current date and time in Python?

I want to make an app that when run, it will get the current date and time from the user's computer, and then count down to a week later at the time of running.
So for example:
The user runs the app on 06-06-2017 11:00:00, it must do a count down to a deadline a week later and display the deadline date and time, and show a count down of how many days, hours, minutes and seconds are left.
EDIT:
So far I have only been able to get the date and time and the time increments normally per second. I am having difficulty decrementing it. Without the last line of the code the time decrements but does not update automatically. I have yet to find a way to perform a count down from a week in advance.
def updateTime():
X = 1
t = datetime.datetime.now()
s = t.replace(microsecond=0)
result = s - datetime.timedelta(seconds=X)
future = s + datetime.timedelta(days=7, hours=0, minutes=0, seconds=0)
lblTime.configure(text=result, font=("", 14))
lblTime.after(100, updateTime)
You definitely want to calculate the target time only once instead of getting it every time the updateTime handler runs. Furthermore, you can simply do arithmetic on datetime objects to get a timedelta object back which you can then display in your GUI.
Here is an example that is printing the output to the console. You can probably adjust this as needed to make it display in your GUI.
import datetime
target_time = datetime.datetime.now() + datetime.timedelta(days=7)
target_time = target_time.replace(microsecond=0)
def get_remaining_time():
delta = target_time - datetime.datetime.now()
hours = delta.seconds // 3600
minutes = (delta.seconds % 3600) // 60
seconds = delta.seconds % 60
print('{} days, {} hours, {} minutes, {} seconds'.format(delta.days, hours, minutes, seconds))
while True:
get_remaining_time()

Setting Loop with start and end date

Thats a code a friend of mine helped me with in order to get files from diferent measurement systems, timestamps and layout into on .csv file.
You enter the timeperiod or like in the case below 1 day and the code looks for this timestamps in different files and folders, adjusts timestamps (different Timezone etc.) and puts everything into one .csv file easy to plot. Now I need to rewrite that stuff for different layouts. I managed to get everything working but now I don't want to enter every single day manually into the code :-( , cause I'd need to enter it 3 times in a row --> in order to get the day for one day into one file, dateFrom and dateTo needs to be the same and in the writecsv...section you'd have to enter the date again.
here's the code:
from importer import cloudIndices, weatherall, writecsv,averagesolar
from datetime import datetime
from datetime import timedelta
dateFrom = datetime.strptime("2010-06-21", '%Y-%m-%d')
dateTo = datetime.strptime("2010-06-21", '%Y-%m-%d')
....
code
code
....
writecsv.writefile("data_20100621", header, ciData)
what can I change here so that I get an automatic loop for all data between e.g 2010-06-21 to 2011-06-21
p.s. if i'd entered 2010-06-21in dataFromand 2011-06-21 in dateTo i'd get a huge cvs. file with all the data in it ..... I thought that would be a great idea but it's not really good for plotting so I enden up manually entering day after day which isn't bad if you do it on a regular basis for 2 or 3 days but now a dates showed up and I need to rund the code over it :-(
Generally speaking you should be using datetime.datetime and datetime.timedelta, here is an example of how:
from datetime import datetime
from datetime import timedelta
# advance 5 days at a time
delta = timedelta(days=5)
start = datetime(year=1970, month=1, day=1)
end = datetime(year=1970, month=2, day=13)
print("Starting from: %s" % str(start))
while start < end:
print("advanced to: %s" % str(start))
start += delta
print("Finished at: %s" % str(start))
This little snippet creates a start and end time and a delta to advance using the tools python provides. You can modify it to fit your needs or apply it in your logic.

Resources