Related
I have tried to create a program to analyze a NEtzwerk folder.
I would like to know between Monday and Friday when, for a selected period, the first file of the day is filed and when the last file of the day is filed.
This way I can see if there are any discrepancies on the same day of the week and between days for the selected time period.
For the last file of the day I want to display the curve in blue and for the first file in red, but for now I have only tried to realize the first curve.
Maybe someone has an idea how I get it to run?
import os
import datetime
import matplotlib.pyplot as plt
def get_first_times(folder_path):
week = {
"Monday": None,
"Tuesday": None,
"Wednesday": None,
"Thursday": None,
"Friday": None,
"Saturday": None,
"Sunday": None
}
for file in os.listdir(folder_path):
file_time = datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(folder_path, file)))
day_of_week = file_time.strftime("%A")
if week[day_of_week] is None or file_time < week[day_of_week]:
week[day_of_week] = file_time
# Wochentage ohne gültige Uhrzeit auf 23:59 setzen
for day, time in week.items():
if time is None:
week[day] = datetime.datetime.strptime("23:59", "%H:%M")
return week
folder_path = "//DEKER/Bench/Data/D10"
first_times = get_first_times(folder_path)
days = list(first_times.keys())
times = [time.strftime("%H:%M") for time in first_times.values()]
plt.plot(days, times)
plt.xlabel("Day of the week")
plt.ylabel("Time")
plt.show()
i'm working on a python flask project that has table named requests
and it gets data or adds data in it
when a new request is submitted, the
current timeis recorded and when it's edited and status set to pending, current time at that time is recorded too in another column.
i made a thread that runs in background to subtract current time from start time and pending time to check for time since request was submitted or pending. however , i need to modify it so that the day is from 08:00 to 16:00 and that's it and if current time is bigger it's simply shifted to the next day's , except for Thursday it's shifted two days
example :
if request is pending at Tuesday 15:00
and today is Wednesday and the time is now 08:30 the subtraction result should be only one and a half hour not 17:30 hours
and make sure to count Friday as holiday
i can try to make it with many conditions and add 16 hours to time but i believe there should be an easier solution. is there any ?
this is the thread with the incomplete bad solution
def monitoring_loop():
while True:
#if datetime.now().strftime("%H:%M:%S")=="15:59:59" or datetime.now().strftime("%H:%M:#%S")=="12:30:00":
session = DBSession()
UserRequests= session.query(Requests).filter(Requests.Status_Name!="Solved").all()
if datetime.now().strftime("%H:%M:%S")>="08:00:00" and datetime.now().strftime("%H:%M:%S")<"15:59:59":
currentTime=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("Saving Changes Normally")
datetimeFormat = '%Y-%m-%d %H:%M:%S'
for req in UserRequests:
if req.Status_Name=="Opened" :
c = datetime.strptime(currentTime, datetimeFormat)- datetime.strptime(str(req.Record_Created), datetimeFormat)
req.OpenedToPending =c.total_seconds()/60
req.PendingToSolved =0
session.add(req)
elif req.Status_Name=="Pending" :
p = datetime.strptime(currentTime, datetimeFormat)- datetime.strptime(str(req.FirstResponseAt), datetimeFormat)
req.PendingToSolved =p.total_seconds()/60
session.add(req)
else:
if datetime.now().strftime("%H:%M:%S")>"16:00:00" and datetime.now().strftime("%H:%M:%S")<="23:59:59":
currentTime=datetime.strptime(datetime.now(), "%Y-%m-%d 08:00:00")+timedelta(days=1)
for req in UserRequests:
if req.Status_Name=="Opened" :
c = datetime.strptime(currentTime, datetimeFormat)- (datetime.strptime(str(req.Record_Created), datetimeFormat)+timedelta(hours=16))
req.OpenedToPending =c.total_seconds()/60
req.PendingToSolved =0
session.add(req)
elif req.Status_Name=="Pending" :
p = datetime.strptime(currentTime, datetimeFormat)- (datetime.strptime(str(req.FirstResponseAt), datetimeFormat)+timedelta(hours=16))
req.PendingToSolved =p.total_seconds()/60
session.add(req)
elif datetime.now().strftime("%H:%M:%S")>"00:00:00" and datetime.now().strftime("%H:%M:%S")<"08:00:00":
currentTime=datetime.strptime(datetime.now(), "%Y-%m-%d 08:00:00")
for req in UserRequests:
if req.Status_Name=="Opened" :
c = datetime.strptime(currentTime, datetimeFormat)- (datetime.strptime(str(req.Record_Created), datetimeFormat)+timedelta(hours=16))
req.OpenedToPending =c.total_seconds()/60
req.PendingToSolved =0
session.add(req)
elif req.Status_Name=="Pending" :
p = datetime.strptime(currentTime, datetimeFormat)- (datetime.strptime(str(req.FirstResponseAt), datetimeFormat)+timedelta(hours=16))
req.PendingToSolved =p.total_seconds()/60
session.add(req)
There is no magic trick as such - but someone else has already thought about this and there is a module businesstimedelta that does what you want it to do:
import datetime
import businesstimedelta
workday = businesstimedelta.WorkDayRule(start_time=datetime.time(8),
end_time=datetime.time(16),
working_days=[0,1,2,3,6])
businesshours = businesstimedelta.Rules([workday])
d1 = datetime.datetime(2020,2,3,14,0,0)
d2 = datetime.datetime(2020,2,4,10,0,0)
d3 = datetime.datetime(2020,2,6,14,0,0)
d4 = datetime.datetime(2020,2,9,10,0,0)
print(businesshours.difference(d1,d2))
print(businesshours.difference(d3,d4))
This defines a working week so that work hours are 8-16 and it declares Friday and Saturday as days off. Then it does some calculations. d1 is a Monday, d2 Tuesday, d3 Thursday and d4 Sunday.
You can customise the working days as you wish, 0 appears to be Monday and 6 Sunday.
I want to get start time and end time of yesterday linux timestamp
import time
startDay = time.strftime('%Y-%m-%d 00:00:00')
print startDay
endDay =time.strftime('%Y-%m-%d 23:59:59')
print endDay
Output is:
2016-11-18 00:00:00
2016-11-18 23:59:59
this showing in string today start-time and end-time
I want to get yesterday start-time and end-time in linux time-stamp
like:
4319395200
4319481599
import time
def datetime_timestamp(dt):
time.strptime(dt, '%Y-%m-%d %H:%M:%S')
s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))
return int(s)
import datetime
midnight2 = datetime.datetime.now().replace(hour=0,minute=0,second=0, microsecond=0)
midnight2 = midnight2 - datetime.timedelta(seconds= +1)
midnight1 = midnight2 - datetime.timedelta(days= +1, seconds= -1)
base = datetime.datetime.fromtimestamp(0)
yesterday = (midnight1 - base).total_seconds()
thismorning = (midnight2 - base).total_seconds()
print midnight1,"timestamp",int(yesterday)
print midnight2,"timestamp",int(thismorning)
print "Seconds elapsed",thismorning - yesterday
Result as of 18/11/2016 :
2016-11-17 00:00:00 timestamp 1479337200
2016-11-17 23:59:59 timestamp 1479423599
Seconds elapsed 86399.0
from datetime import datetime, date, time, timedelta
# get start of today
dt = datetime.combine(date.today(), time(0, 0, 0))
# start of yesterday = one day before start of today
sday_timestamp = int((dt - timedelta(days=1)).timestamp())
# end of yesterday = one second before start of today
eday_timestamp = int((dt - timedelta(seconds=1)).timestamp())
print(sday_timestamp)
print(eday_timestamp)
Or:
# get timestamp of start of today
dt_timestamp = int(datetime.combine(date.today(), time(0, 0, 0)).timestamp())
# start of yesterday = start of today - 86400 seconds
sday_timestamp = dt_timestamp - 86400
# end of yesterday = start of today - 1 second
eday_timestamp = dt_timestamp - 1
Use the power of perl command , no need to import time.
Startday=$(perl -e 'use POSIX;print strftime "%Y-%-m-%d 00:00:00",localtime time-86400;')
Endday=$(perl -e 'use POSIX;print strftime "%Y-%-m-%d 23:59:59",localtime time-86400;')
echo $Startday
echo $Endday
or
startday=date --date='1 day ago' +%Y%m%d\t00:00:00
startday=date --date='1 day ago' +%Y%m%d\t23:59:59
echo $Startday
echo $Endday
Stack Overflow is my Q&A bible, so first, a massive thanks to all of you contributes out there. You all make my life easier as a developer and save me so much time.
I want to preface my question by saying that I am still pretty new to Python in general, and I come from a background of Java programming predominantly. There is likely a lot of problems in my code as I am still learning the quirks of Python. Be gentle please!
I'm creating an events management application using Django, and I've run into some sort of referencing problem. In the view below, a list of events is created per day of a given week from the day that the view is accessed in the application. I am creating a pre-formatted HTML line of a table to then be displayed in the corresponding template, and adding this to each 'day' object within the list. This seems archaic, I know; why wouldn't I use JS to do this in my view? Reasoning is that I am trying to stay away from depending on JS for the app to function correctly.
The code references the first and last objects(events) in a sorted list, to determine both the starting time of the earliest event and the finishing time of the latest event, which determines how many blank TDs are placed before and after each event, and also the colspan(duration) of the event. in half hour resolution. However, depending on the current iteration of the for loop in my template, these references are changing, for some reason that I cannot understand. I've spent hours trying to grok this, and have tried many different solutions to no avail.
Additionally, I have noticed that the length of my events list seems to be being reduced by one for every iteration, as if a 'pop' function is automatically taking place... I don't get this!
All imports are correct and included at the top of views.py. I didn't see it as necessary to include them.
The function:
def getWeekView(currDay): #currDay is simply datetime.now()
week_view = []
events = []
daily = list(Event.objects.filter(how_often='daily')) #copy querysets to lists to ease DB queries
weekly = list(Event.objects.filter(how_often='weekly'))
for day in xrange(0, 7, 1):
searchRange = [datetime(currDay.year, currDay.month, currDay.day, 0, 0, 0), datetime(currDay.year, currDay.month, currDay.day, 23, 59, 59)]
events = list(Event.objects.filter(date__range=searchRange, is_repeat=False))
for event in daily: #copy recurring events into events list
if is_open(event.business, currDay.isoweekday()):
events.append(event)
for event in weekly:
if (event.date).isoweekday() == currDay.isoweekday() and is_open(event.business, currDay.isoweekday()):
events.append(event)
events = sorted(events, key=lambda event: (event.date).time())
if len(events) > 0:
earliest_time = (events[0].date).time()
latest_time = (events[len(events)-1].end).time()
earliest = Decimal(earliest_time.hour) + (Decimal(earliest_time.minute)/60)
latest = Decimal(latest_time.hour) + (Decimal(latest_time.minute)/60)
blocks = []
x = earliest
while x <= latest:
if x % 1 != 0:
blocks.append("%s:%s" % (str(int(floor(x))), '30'))
else:
blocks.append("%s:%s" % (str(int(x)), '00'))
x = x+Decimal(0.5)
for event in events:
end_time = (event.end).time()
start_time = (event.date).time()
end = Decimal(end_time.hour) + (Decimal(end_time.minute)/60)
start = Decimal(start_time.hour) + (Decimal(start_time.minute)/60)
duration = (end - start)*2 #multiply by two for 1/2hr resolution in the resultant table
temp = "<tr>"
x = earliest
while x < start:
temp = "%s%s" % (temp, "<td> </td>")
x = x+Decimal(0.5)
if duration > 1:
# I changed this to output variables for the purposes of debugging the issue. Normally the commented line underneath this would apply.
temp += """<td colspan="%s">earliest_time:%s latest_time:%s earliest:%s latest:%s start:%s end:%s duration:%s x:%s len of events:%s</td>""" % (int(duration), earliest_time, latest_time, earliest, latest, start, end, duration, x, len(events))
#temp += """<td colspan="%s">%s</td>""" % (int(duration), reverse('event_detail', args=[event.pk]),event.title)
else:
temp += """<td>%s</td>""" % (reverse('event_detail', args=[event.pk]),event.title)
x += duration
while x < latest:
temp += '<td> </td>'
x += Decimal(0.5)
temp += '</tr>'
event.row = temp
week_view.append({'day':currDay.strftime('%a, %x'), 'events':events, 'blocks':blocks})
else:
week_view.append({'day':currDay.strftime('%a, %x')})
currDay += timedelta(days=1)
return week_view
Sample textual Output:
Fri, 04/18/14
3:00 3:30 4:00 4:30 5:00 5:30 6:00 6:30 7:00 7:30
earliest_time:03:00:00 latest_time:07:30:00 earliest:3 latest:7.5 start:3 end:5.5 duration:5.0 x:3 len of events:2
earliest_time:05:30:00 latest_time:07:30:00 earliest:5.5 latest:7.5 start:5.5 end:7.5 duration:4.0 x:5.5 len of events:1
Sat, 04/19/14
5:30 6:00 6:30 7:00 7:30
earliest_time:05:30:00 latest_time:07:30:00 earliest:5.5 latest:7.5 start:5.5 end:7.5 duration:4.0 x:5.5 len of events:1
Sun, 04/20/14
No Events Listed
Mon, 04/21/14
5:30 6:00 6:30 7:00 7:30
earliest_time:05:30:00 latest_time:07:30:00 earliest:5.5 latest:7.5 start:5.5 end:7.5 duration:4.0 x:5.5 len of events:1
Tue, 04/22/14
5:30 6:00 6:30 7:00 7:30
earliest_time:05:30:00 latest_time:07:30:00 earliest:5.5 latest:7.5 start:5.5 end:7.5 duration:4.0 x:5.5 len of events:1
Wed, 04/23/14
5:30 6:00 6:30 7:00 7:30
earliest_time:05:30:00 latest_time:07:30:00 earliest:5.5 latest:7.5 start:5.5 end:7.5 duration:4.0 x:5.5 len of events:1
Thu, 04/24/14
5:30 6:00 6:30 7:00 7:30
earliest_time:05:30:00 latest_time:07:30:00 earliest:5.5 latest:7.5 start:5.5 end:7.5 duration:4.0 x:5.5 len of events:1
The related Django model:
class Event(models.Model):
DAILY = 'daily'
WEEKLY = 'weekly'
REPEAT_CHOICES = (
(DAILY, 'Daily'),
(WEEKLY, 'Weekly'),
)
title = models.CharField(max_length=25, help_text="Please enter the name of your event")
description = models.CharField(max_length=255, help_text="Please enter a description of your event")
date = models.DateTimeField(help_text="Please select the date and start time of your event")
end = models.DateTimeField(help_text="Please select the end time / date that your event will finish")
business = models.ForeignKey(Business)
category = models.ManyToManyField(Category, help_text="Please select the category(ies) of your event")
is_repeat = models.BooleanField(default=False, help_text="Please select whether your event will repeat")
how_often = models.CharField(max_length=7, blank=True, choices=REPEAT_CHOICES, help_text="Please select how often your event will repeat")
def __unicode__(self):
return unicode(self.title)
Code from the template responsible for iterating through the week object and outputting to browser:
<div>
<table id="index-table">
<tr><th>Date</th><th>Events</th></tr>
{% for day in week_obj %}
<tr><td>{{ day.day }}</td>
<td>{% if day.events %}<table id="events-table{{ forloop.counter }}" class="table"><tbody><tr>{% for block in day.blocks %}<th>{{ block }}</th>{% endfor %}{% for event in day.events %}{{ event.row|safe }}{% endfor %}</tbody></table>{% else %}No Events Listed{% endif %}</td>
</tr>
{% endfor %}
</table>
</div>
I really appreciate any help anybody out there can offer on this. I am most perplexed, and I want to understand why Python behaves like this (or what the hell I am doing to cause it to do so!)
Additionally, I am always open to suggestions on how I can make my code better. Be as critical as you like, I need to learn.
Many thanks!
Others with actual Django experience can help with the general questions. In any case, with respect to your immediate issue:
for day in xrange(0, 7, 1):
searchRange = [datetime(currDay.year, currDay.month, currDay.day, 0, 0, 0), datetime(currDay.year, currDay.month, currDay.day, 23, 59, 59)]
events = list(Event.objects.filter(date__range=searchRange, is_repeat=False))
# etc.
currDay += timedelta(days=1)
At the beginning of each iteration, you redefine events using a filter defined with a range starting one day ahead (given the update to currDay at the end of the iteration). Therefore, events[0] changes and events gets one element shorter each iteration.
A specific bank has branches in all major cities in the world. They all open at 10:00 AM local time. If within a timezone that uses DST, then of course the local opening time also follows the DST-adjusted time. So how do I go from the local time to the utc time.
What I need is a function to_utc(localdt, tz) like this:
Arguments:
localdt: localtime, as naive datetime object, DST-adjusted
tz: timezone in the TZ-format, e.g. 'Europe/Berlin'
Returns:
datetime object, in UTC, timezone-aware
EDIT:
The biggest challenge is to detect whether the local time is in a period with DST, which also means that it is DST adjusted.
For 'Europe/Berlin' which has +1 DST in the summer:
Jan 1st 10:00 => Jan 1st 9:00 UTC
July 1st 10:00 => July 1st 8:00 UTC
For 'Africa/Lagos' which has no DST:
Jan 1st 10:00 => Jan 1st 9:00 UTC
July 1st 10:00 => July 1st 9:00 UTC
Using pytz, and in particular its localize method:
import pytz
import datetime as dt
def to_utc(localdt,tz):
timezone=pytz.timezone(tz)
utc=pytz.utc
return timezone.localize(localdt).astimezone(utc)
if __name__=='__main__':
for tz in ('Europe/Berlin','Africa/Lagos'):
for date in (dt.datetime(2011,1,1,10,0,0),
dt.datetime(2011,7,1,10,0,0),
):
print('{tz:15} {l} --> {u}'.format(
tz=tz,
l=date.strftime('%b %d %H:%M'),
u=to_utc(date,tz).strftime('%b %d %H:%M %Z')))
yields
Europe/Berlin Jan 01 10:00 --> Jan 01 09:00 UTC
Europe/Berlin Jul 01 10:00 --> Jul 01 08:00 UTC
Africa/Lagos Jan 01 10:00 --> Jan 01 09:00 UTC
Africa/Lagos Jul 01 10:00 --> Jul 01 09:00 UTC
from datetime import datetime, tzinfo, timedelta
class GMT1(tzinfo):
def utcoffset(self, dt):
return timedelta(hours=1)
def dst(self, dt):
return timedelta(0)
def tzname(self,dt):
return "Europe/Prague"
year, month, day = 2011, 7, 23
dt = datetime(year, month, day, 10)
class UTC(tzinfo):
def utcoffset(self, dt):
return timedelta(0)
def dst(self, dt):
return timedelta(0)
def tzname(self,dt):
return "UTC"
def utc(localt, tz):
return localt.replace(tzinfo=tz).astimezone(UTC())
print utc(dt, GMT1())
New Version. This does what you want -- takes a naive datetime and a timezone and returns a UTC datetime.