I need my script to download a new file, if the old one is old enough. I set the maximum age of file in seconds. So that I would get back on track with my script writing I need example code, where file age is printed out in seconds.
This shows how to find a file's (or directory's) last modification time:
Here are the number of seconds since the Epoch, using os.stat
import os
st=os.stat('/tmp')
mtime=st.st_mtime
print(mtime)
# 1325704746.52
Or, equivalently, using os.path.getmtime:
print(os.path.getmtime('/tmp'))
# 1325704746.52
If you want a datetime.datetime object:
import datetime
print("mdatetime = {}".format(datetime.datetime.fromtimestamp(mtime)))
# mdatetime = 2012-01-04 14:19:06.523398
Or a formated string using time.ctime
import stat
print("last accessed => {}".format(time.ctime(st[stat.ST_ATIME])))
# last accessed => Wed Jan 4 14:09:55 2012
print("last modified => {}".format(time.ctime(st[stat.ST_MTIME])))
# last modified => Wed Jan 4 14:19:06 2012
print("last changed => {}".format(time.ctime(st[stat.ST_CTIME])))
# last changed => Wed Jan 4 14:19:06 2012
Although I didn't show it, there are equivalents for finding the access time and change time for all these methods. Just follow the links and search for "atime" or "ctime".
Another approach (I know I wasn't the first answer but here goes anyway):
import time, os, stat
def file_age_in_seconds(pathname):
return time.time() - os.stat(pathname)[stat.ST_MTIME]
The accepted answer does not actually answer the question, it just gives the answer for last modification time. For getting the file age in seconds, minutes or hour you can do this.
import os, time
def file_age(filepath):
return time.time() - os.path.getmtime(filepath)
seconds = file_age('myFile.txt') # 7200 seconds
minutes = int(seconds) / 60 # 120 minutes
hours = minutes / 60 # 2 hours
Use stat.M_TIME to get the last modified time and subtract it from the current time.
http://docs.python.org/library/stat.html
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os, time
def file_age_in_seconds(filename):
try:
return int(time.time() - os.path.getmtime(filename))
except:
#on any failure condition
return -1
filename = "/tmp/foobar.txt"
print(file_age_in_seconds(filename)) #prints -1
f = open(filename, 'w')
f.write("this is a line")
f.close()
print(file_age_in_seconds(filename)) #prints 0
time.sleep(4.2)
print(file_age_in_seconds(filename)) #prints 4
This will do in days, can be modified for seconds also:
#!/usr/bin/python
import os
import datetime
from datetime import date
t1 = os.path.getctime("<filename>")
now = datetime.datetime.now()
Y1 = int(datetime.datetime.fromtimestamp(int(t1)).strftime('%Y'))
M1 = int(datetime.datetime.fromtimestamp(int(t1)).strftime('%m'))
D1 = int(datetime.datetime.fromtimestamp(int(t1)).strftime('%d'))
date1 = date(Y1, M1, D1)
Y2 = int(now.strftime('%Y'))
M2 = int(now.strftime('%m'))
D2 = int(now.strftime('%d'))
date2 = date(Y2, M2, D2)
diff = date2 - date1
days = diff.days
You can get it by using OS and datetime lib in python:
import os
from datetime import datetime
def fileAgeInSeconds(directory, filename):
file = os.path.join(directory, filename)
if os.path.isfile(file):
stat = os.stat(file)
try:
creation_time = datetime.fromtimestamp(stat.st_birthtime)
except AttributeError:
creation_time = datetime.fromtimestamp(stat.st_mtime)
curret_time = datetime.now()
duration = curret_time - creation_time
duration_in_s = duration.total_seconds()
return duration_in_s
else:
print('%s File not found' % file)
return 100000
#Calling the function
dir=/tmp/
fileAgeInSeconds(dir,'test.txt')
Related
How can I run a function in Python, at a given time?
For example:
run_it_at(func, '2012-07-17 15:50:00')
and it will run the function func at 2012-07-17 15:50:00.
I tried the sched.scheduler, but it didn't start my function.
import time as time_module
scheduler = sched.scheduler(time_module.time, time_module.sleep)
t = time_module.strptime('2012-07-17 15:50:00', '%Y-%m-%d %H:%M:%S')
t = time_module.mktime(t)
scheduler_e = scheduler.enterabs(t, 1, self.update, ())
What can I do?
Reading the docs from http://docs.python.org/py3k/library/sched.html:
Going from that we need to work out a delay (in seconds)...
from datetime import datetime
now = datetime.now()
Then use datetime.strptime to parse '2012-07-17 15:50:00' (I'll leave the format string to you)
# I'm just creating a datetime in 3 hours... (you'd use output from above)
from datetime import timedelta
run_at = now + timedelta(hours=3)
delay = (run_at - now).total_seconds()
You can then use delay to pass into a threading.Timer instance, eg:
threading.Timer(delay, self.update).start()
Take a look at the Advanced Python Scheduler, APScheduler: http://packages.python.org/APScheduler/index.html
They have an example for just this usecase:
http://packages.python.org/APScheduler/dateschedule.html
from datetime import date
from apscheduler.scheduler import Scheduler
# Start the scheduler
sched = Scheduler()
sched.start()
# Define the function that is to be executed
def my_job(text):
print text
# The job will be executed on November 6th, 2009
exec_date = date(2009, 11, 6)
# Store the job in a variable in case we want to cancel it
job = sched.add_date_job(my_job, exec_date, ['text'])
Might be worth installing this library: https://pypi.python.org/pypi/schedule, basically helps do everything you just described. Here's an example:
import schedule
import time
def job():
print("I'm working...")
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
while True:
schedule.run_pending()
time.sleep(1)
Here's an update to stephenbez' answer for version 3.5 of APScheduler using Python 2.7:
import os, time
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
def tick(text):
print(text + '! The time is: %s' % datetime.now())
scheduler = BackgroundScheduler()
dd = datetime.now() + timedelta(seconds=3)
scheduler.add_job(tick, 'date',run_date=dd, args=['TICK'])
dd = datetime.now() + timedelta(seconds=6)
scheduler.add_job(tick, 'date',run_date=dd, kwargs={'text':'TOCK'})
scheduler.start()
print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
try:
# This is here to simulate application activity (which keeps the main thread alive).
while True:
time.sleep(2)
except (KeyboardInterrupt, SystemExit):
# Not strictly necessary if daemonic mode is enabled but should be done if possible
scheduler.shutdown()
I've confirmed the code in the opening post works, just lacking scheduler.run(). Tested and it runs the scheduled event. So that is another valid answer.
>>> import sched
>>> import time as time_module
>>> def myfunc(): print("Working")
...
>>> scheduler = sched.scheduler(time_module.time, time_module.sleep)
>>> t = time_module.strptime('2020-01-11 13:36:00', '%Y-%m-%d %H:%M:%S')
>>> t = time_module.mktime(t)
>>> scheduler_e = scheduler.enterabs(t, 1, myfunc, ())
>>> scheduler.run()
Working
>>>
I ran into the same issue: I could not get absolute time events registered with sched.enterabs to be recognized by sched.run. sched.enter worked for me if I calculated a delay, but is awkward to use since I want jobs to run at specific times of day in particular time zones.
In my case, I found that the issue was that the default timefunc in the sched.scheduler initializer is not time.time (as in the example), but rather is time.monotonic. time.monotonic does not make any sense for "absolute" time schedules as, from the docs, "The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid."
The solution for me was to initialize the scheduler as
scheduler = sched.scheduler(time.time, time.sleep)
It is unclear whether your time_module.time is actually time.time or time.monotonic, but it works fine when I initialize it properly.
dateSTR = datetime.datetime.now().strftime("%H:%M:%S" )
if dateSTR == ("20:32:10"):
#do function
print(dateSTR)
else:
# do something useful till this time
time.sleep(1)
pass
Just looking for a Time of Day / Date event trigger:
as long as the date "string" is tied to an updated "time" string, it works as a simple TOD function. You can extend the string out to a date and time.
whether its lexicographical ordering or chronological order comparison,
as long as the string represents a point in time, the string will too.
someone kindly offered this link:
String Comparison Technique Used by Python
had a really hard time getting these answers to work how i needed it to,
but i got this working and its accurate to .01 seconds
from apscheduler.schedulers.background import BackgroundScheduler
sched = BackgroundScheduler()
sched.start()
def myjob():
print('job 1 done at: ' + str(dt.now())[:-3])
dt = datetime.datetime
Future = dt.now() + datetime.timedelta(milliseconds=2000)
job = sched.add_job(myjob, 'date', run_date=Future)
tested accuracy of timing with this code:
at first i did 2 second and 5 second delay, but wanted to test it with a more accurate measurement so i tried again with 2.55 second delay and 5.55 second delay
dt = datetime.datetime
Future = dt.now() + datetime.timedelta(milliseconds=2550)
Future2 = dt.now() + datetime.timedelta(milliseconds=5550)
def myjob1():
print('job 1 done at: ' + str(dt.now())[:-3])
def myjob2():
print('job 2 done at: ' + str(dt.now())[:-3])
print(' current time: ' + str(dt.now())[:-3])
print(' do job 1 at: ' + str(Future)[:-3] + '''
do job 2 at: ''' + str(Future2)[:-3])
job = sched.add_job(myjob1, 'date', run_date=Future)
job2 = sched.add_job(myjob2, 'date', run_date=Future2)
and got these results:
current time: 2020-12-10 19:50:44.632
do job 1 at: 2020-12-10 19:50:47.182
do job 2 at: 2020-12-10 19:50:50.182
job 1 done at: 2020-12-10 19:50:47.184
job 2 done at: 2020-12-10 19:50:50.183
accurate to .002 of a second with 1 test
but i did run a lot of tests and accuracy ranged from .002 to .011
never going under the 2.55 or 5.55 second delay
#everytime you print action_now it will check your current time and tell you should be done
import datetime
current_time = datetime.datetime.now()
current_time.hour
schedule = {
'8':'prep',
'9':'Note review',
'10':'code',
'11':'15 min teabreak ',
'12':'code',
'13':'Lunch Break',
'14':'Test',
'15':'Talk',
'16':'30 min for code ',
'17':'Free',
'18':'Help ',
'19':'watever',
'20':'watever',
'21':'watever',
'22':'watever'
}
action_now = schedule[str(current_time.hour)]
I'm looking for a conversion of just am/pm string into time so I could do comparison between 2 different time of the day. I tried using time.strptime or something similar but it seems they all require date as well as time.
My code below:
current_hour = 12
current_minute = 37
current_section = "PM"
due_hour = 9
due_minute = 0
due_section = "AM"
import datetime
ct_time = str(datetime.time(current_hour, current_minute))+current_section
print(ct_time)
due_time = str(datetime.time(due_hour, due_minute))+due_section
print(due_time)
ct_time_str = time.strptime(ct_time, '%H:%M:%S') # how to format this to time?
due_time_str= time.strptime(due_time,'%H:%M:%S') # how to format this to time?
if (ct_time_str>due_time_str):
print("still have time to turn in assignment")
else:
print("too late")
Getting the below error, not sure how to convert to 'time' from str.
Traceback (most recent call last):
File "main.py", line 15, in <module>
ct_time_str = time.strptime(ct_time, '%H:%M:%S')
NameError: name 'time' is not defined
datetime can be confusing because both the module and class are called datetime.
Change your import to from datetime import datetime, time. Also imports should go at the very top, but it's not strictly necessary.
When assigning ct_time and due_time, you use str(datetime.time(args)), it should just be str(time(args)).
strptime is from datetime, not time, so change time.strptime(args) to datetime.strptime(args)
Also like DeepSpace & martineau said, you need to add '%p' to the format string to account for the AM/PM part.
Final code:
from datetime import datetime, time
current_hour = 12
current_minute = 37
current_section = "PM"
due_hour = 9
due_minute = 0
due_section = "AM"
ct_time = str(time(current_hour, current_minute))+current_section
print(ct_time)
due_time = str(time(due_hour, due_minute))+due_section
print(due_time)
ct_time_str = datetime.strptime(ct_time, '%H:%M:%S%p')
due_time_str= datetime.strptime(due_time,'%H:%M:%S%p')
if (ct_time_str < due_time_str):
print("still have time to turn in assignment")
else:
print("too late")
edit:
changed if (ct_time_str < due_time_str): to if (ct_time_str > due_time_str):
Hi Everyone i have googles to my hearts content but have not found the answer.
Basically I want to add user inputted time to the current time.
This is just a small project I'm working on while learning Python.
So if the current time is 17:16 and the user wants to add 1hr 30 to that. how would i do it.
This is what i have:
import datetime
flex = input("Enter your flex amount in HHMM:")
flex = flex[0]+flex[1]+"-"+flex[2]+flex[3]
time = datetime.datetime.now().strftime("%H-%M")
balance = time+flex
print(time)
print(flex)
print(balance)
I have now tried
import datetime
flex = input("Enter your flex amount in HHMM:")
time = datetime.datetime.now().strftime("%H-%M")
flex = flex[0]+flex[1]+"-"+flex[2]+flex[3]
time = time[0]+time[1]+"-"+time[2]+time[3]
balance = datetime.timedelta(hours=int(time[0]+time[1]),
minutes=int(time[2]+time[3]) +
datetime.timedelta(hours=int(flex[0]+flex[1]),
minutes=int(flex[2]+flex[3]))
But now its complaining about its expecting an integer. but if i change it ot an integer will that not defeat the purpose of me wanting to add is as time.
Thanks
I got it to work using the answer. This is what it looks like now thanks pal.
from datetime import timedelta as td
import datetime as da
#flex = input("Enter your flex amount in HHMM:")
flex = "0134"
now = da.datetime.now()
user_hours = int(flex[:2])
user_minute = int(flex[2:5])
delay = td(hours=user_hours, minutes=user_minute)
balance = da.datetime.now()+delay
print("Lunch: " +str(lunch))
print("Time when balance at 00:00 : " +str(balance))
print("Now: " +str(now))
Simple using timedelta create an offset indicated by timedelta object and ad it to your time object (working the same with date and datetime too).
from datetime import timedelta, datetime
actual_time = datetime.now()
user_hours = int(flex[:3])
user_minute = int(flex[2:5])
delay = timedelta(hours=user_hours, minutes=user_minute)
print(datetime.now()+delay)
So if the current time is 17:16 and the user wants to add 1hr 30 to
that. how would i do it.
You can use timedelta, i.e.:
new_time = datetime.datetime.now() + datetime.timedelta(hours=1, minutes=30) # or simply minutes=90, etc...
Cool so when tring
balance = datetime.timedelta(hours=int(time[0]+time[1]), minutes=int(time[2]+time[3]) + datetime.timedelta(hours=int(flex[0]+flex[1]), minutes=int(flex[2]+flex[3]))
its complaining that its expecting an interger not a time delta
I'm looking to control a script via Zigbee/XBee using X-CTU. I've created a script named zb_control.py. Now I'm trying to start and stop another script within this script. A script adxl345test.py is used to collect data from an attached accelerometer on my Raspberry Pi.
The idea behind the zb_control.py script is that I run it and then if I type "run" in X-CTU the script will start running adxl345test.py and collect data.
I'm trying to create a script within a script that can also be stopped again and then still have the zb_control.py running ready to recieve new input from X-CTU.
As you can tell I've tried different things:
import serial, time, sys, os, subprocess
from subprocess import check_call
from subprocess import call
while True:
ser=serial.Serial('/dev/ttyUSB0',9600,timeout=2)
inc=ser.readline().strip()
if inc=='run':
print("---------------")
print("Collecting data")
print("---------------")
p = subprocess.Popen("/home/pi/adxl345test.py", stdout=subprocess.PIPE, shell=True)
elif inc=='stop':
# check_call(["pkill", "-9", "-f", adxl345test.py])
# serial.write('\x03')
# os.system("pkill –f adxl345test.py")
# call(["killall", "adxl345test.py"])
p.kill()
print("-----------------------")
print("Script has been stopped")
print("-----------------------")
I got it to run and it's now collecting data properly. However now the problem is stopping the adxl345test.py again. As you can tell from the script from above I'm using p.kill() but the script doesn't stop collecting data. When I type "stop" in XCTU my zb_control.py does print the print-commands but the p.kill() isn't being executed. Any suggestions?
I've tried using p.terminate() alone and together with p.kill() aswell as the commands by themselves however it doesn't stop the adxl345test.py script. I can tell that the .csv-file is still increasing in size and therefore the script must still be collecting data.
Here is the adxl345test.py script for those interested:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Example on how to read the ADXL345 accelerometer.
# Kim H. Rasmussen, 2014
import sys, math, os, spidev, datetime, ftplib
# Setup SPI
spi = spidev.SpiDev()
#spi.mode = 3 <-- Important: Do not do this! Or SPI won't work as intended, or even at all.
spi.open(0,0)
spi.mode = 3
# Read the Device ID (should be xe5)
id = spi.xfer2([128,0])
print 'Device ID (Should be 0xe5):\n'+str(hex(id[1])) + '\n'
# Read the offsets
xoffset = spi.xfer2([30 | 128,0])
yoffset = spi.xfer2([31 | 128,0])
zoffset = spi.xfer2([32 | 128,0])
accres = 2
accrate = 13
print 'Offsets: '
print xoffset[1]
print yoffset[1]
# print str(zoffset[1]) + "\n\nRead the ADXL345 every half second:"
# Initialize the ADXL345
def initadxl345():
# Enter power saving state
spi.xfer2([45, 0])
# Set data rate to 100 Hz. 15=3200, 14=1600, 13=800, 12=400, 11=200, 10=100 etc.
spi.xfer2([44, accrate])
# Enable full range (10 bits resolution) and +/- 16g 4 LSB
spi.xfer2([49, accres])
# Enable measurement
spi.xfer2([45, 8])
# Read the ADXL x-y-z axia
def readadxl345():
rx = spi.xfer2([242,0,0,0,0,0,0])
#
out = [rx[1] | (rx[2] << 8),rx[3] | (rx[4] << 8),rx[5] | (rx[6] << 8)]
# Format x-axis
if (out[0] & (1<<16 - 1 )):
out[0] = out[0] - (1<<16)
# out[0] = out[0] * 0.004 * 9.82
# Format y-axis
if (out[1] & (1<<16 - 1 )):
out[1] = out[1] - (1<<16)
# out[1] = out[1] * 0.004 * 9.82
# Format z-axis
if (out[2] & (1<<16 - 1 )):
out[2] = out[2] - (1<<16)
# out[2] = out[2] * 0.004 * 9.82
return out
# Initialize the ADXL345 accelerometer
initadxl345()
# Read the ADXL345 every half second
timetosend = 60
while(1):
with open('/proc/uptime','r') as f: # get uptime
uptime_start = float(f.readline().split()[0])
uptime_last = uptime_start
active_file_first = "S3-" + str(pow(2,accrate)*25/256) + "hz10bit" + str(accres) + 'g' + str(datetime.datetime.utcnow().strftime('%y%m%d%H%M')) $
active_file = active_file_first.replace(":", ".")
wStream = open('/var/log/sensor/' + active_file,'wb')
finalcount = 0
print "Creating " + active_file
while uptime_last < uptime_start + timetosend:
finalcount += 1
time1 = str(datetime.datetime.now().strftime('%S.%f'))
time2 = str(datetime.datetime.now().strftime('%M'))
time3 = str(datetime.datetime.now().strftime('%H'))
time4 = str(datetime.datetime.now().strftime('%d'))
time5 = str(datetime.datetime.now().strftime('%m'))
time6 = str(datetime.datetime.now().strftime('%Y'))
axia = readadxl345()
wStream.write(str(round(float(axia[0])/1024,3))+','+str(round(float(axia[1])/1024,3))+','+str(round(float(axia[2])/1024,3))+','+time1+','+ti$
# Print the reading
# print axia[0]
# print axia[1]
# print str(axia[2]) + '\n'
# elapsed = time.clock()
# current = 0
# while(current < timeout):
# current = time.clock() - elapsed
with open('/proc/uptime', 'r') as f:
uptime_last = float(f.readline().split()[0])
wStream.close()
def doftp(the_active_file):
session = ftplib.FTP('192.0.3.6','sensor3','L!ghtSp33d')
session.cwd("//datalogger//")
file = open('/var/log/sensor/' + active_file, 'rb') # file to send
session.storbinary('STOR' + active_file, file) # send the file
file.close()
session.quit
My suggestions:
If you're doing something at a specified interval, you're probably better off using threading.Timer rather than checking the time yourself.
As I said in the comment, you can check for an exit condition instead of brutally killing the process. This also allows to properly clean up what you need.
Those time1...time6 really don't look nice, how about a list? Also, time2, time3, time4, time5, time6 are not used.
You don't actually need strftime to get hour, day, month, year, etc. They're already there as attributes.
You can do something like:
cur_time = datetime.datetime.now()
cur_hour = cur_time.hour
cur_minute = cur_time.minute
...And so on, which is a bit better. In this specific case it won't matter, but if you start measuring milliseconds, the time will be slightly different after a few lines of code, so you should store it and use it from the variable.
As for the rest, if you want an example, here I check that a file exists to determine whether to stop or not. It's very crude but it should give you a starting point:
from threading import *
from os.path import exists
def hello():
print('TEST') # Instead of this, do what you need
if (exists('stop_file.txt')):
return
t = Timer(0.5, hello)
t.start()
hello()
Then in the other create you create the stop file when you want it to stop (don't forget to add a line to remove it before starting it again).
I want to add hours and minutes to a time, using variables. So, in the example below, instead of having 'hours=3, minutes=30', I would like to have 3 and 30 stored in variables.
Is this possible?
import datetime
now = datetime.datetime.now()
ahead_time = now + datetime.timedelta(hours=3,minutes=30)
print(" now time is ", now, " ahead_time is ", ahead_time)
Thanks.
By using command line you can write like below
import datetime
import argparse
def getTime(hour, minutes):
now = datetime.datetime.now()
ahead_time = now + datetime.timedelta(hours=int(hour),minutes=int(minutes))
return " now time is %s ahead_time is %s" %(now, ahead_time)
def parser():
parser = argparse.ArgumentParser(description='Process the input time.')
parser.add_argument('--hour', dest='hour')
parser.add_argument('--minutes', dest='minutes')
return vars(parser.parse_args())
if __name__ == "__main__":
args = parser()
hour = args.get('hour', None)
minutes = args.get('minutes', None)
if hour and minutes:
print getTime(hour, minutes)
Usage:
$ python test.py --hour 3 --minutes 30
now time is 2017-03-23 06:37:49.890000 ahead_time is 2017-03-23 10:07:49.890000