Python Defining Business days and working hours - python-3.x

I am looking for guidance on how to create a variable (Business_Time) which contains only business days (not weekends) and where i can set working hours (9am - 6pm GMT).
The reason for this is because i'm trying to calculate some SLA's (how long employees have to complete a task), however if the end time falls outside of these business days/hours, then i can set it to a specific time.
Many thanks

pandas already implement BusinessHour and BusinessDay:
from pandas.tseries.offsets import BusinessDay
from pandas.tseries.offsets import BusinessHour
from dateutil import parser
myDate = parser.parse('Fri, 7 Jan 2022 17:00:00 +0000 (UTC)')
myWorkTime = BusinessDay(1) + BusinessHour(1)
print(myDate + myWorkTime)
This will print Timestamp('2022-01-11 10:00:00+0000', tz='tzutc()').
You can find a lot of tutorials over the internet (like this one for example)

Related

Get Current Day w.r.t timezone [duplicate]

This question already has answers here:
Display the time in a different time zone
(12 answers)
Python get current time in right timezone [duplicate]
(1 answer)
Closed 3 years ago.
The following code snippet print the day for example. Monday (or) Tuesday etc..
But on my local machine its printing as per Indian Standard time Timezone but on my server, its printing as per UTC.
import datetime
from datetime import date
current_day_name = (date.today().strftime("%A")).lower()
print(current_day_name)
Can someone please suggest how do i tweak this code as per a specific timezone like Indian Standard Time (or) UTC?
Here is a quote from the datetime library reference:
Because the format depends on the current locale, care should be taken when making assumptions about the output value.
So datetime depends on the locale settings. The locale reference describes a function setlocale:
Applications typically start with a call of:
import locale
locale.setlocale(locale.LC_ALL, '')
So, first make sure you have whichever language-pack you need (e.g. sudo apt install language-pack-id) then specify the locale as described in the documentation.
As an example, on my computer I run
>>>import locale
>>>locale.getdefaultlocale()
('en_US', 'UTF-8')
>>>datetime.date.today().strftime('%A')
'Saturday'
>>> locale.setlocale(locale.LC_ALL,'hr_HR.utf8')
'hr_HR.utf8'
>>> datetime.date.today().strftime('%A')
'subota'
It looks like you might also need to supply tzinfo to your datetime constructor (see the datetime reference). For example:
>>> datetime.datetime.now(datetime.timezone.utc).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 01:07:16 PM , UTC,+0000'
>>> datetime.datetime.now(datetime.timezone(
datetime.timedelta(hours=1),'CET')).strftime('%c, %Z,%z')
'Sat 15 Feb 2020 02:07:28 PM , CET,+0100'

Handling Daylight Saving Time

In Python 3.x, I want to capture current time along with its timezone and then convert it into Unix timestamp and sent to a server.
I have tried various libraries like pytz, arrow, moment, pendulum, but I am not sure how to deal with daylight saving time (DST). Currently, I am using time.tzname to get timezone information but it specifically showing India in DST. In reality India never follows DST.
The library pytz should work pretty well. You need to use the function dst() from that library to check if a timezone is under daylight savings influence.
https://medium.com/#nqbao/python-timezone-and-daylight-savings-e511a0093d0
From the link above:
>>> import pytz
>>> pst = pytz.timezone("US/Pacific")
>>> pst.localize(datetime(2017, 10, 1)).dst()
datetime.timedelta(0, 3600)
>>> pst.localize(datetime(2017, 12, 1)).dst()
datetime.timedelta(0)
Understanding offset naive and offset aware date times will make your life much easier.
This helped me in resolving the issue using time.tzname
if time.tzname[1] is None or time.tzname[0] == time.tzname[1]:
timezone = time.localtime().tm_zone
# no DST
timezone = time.tzname[0]
else:
# we're in DST
timezone = time.tzname[1]

Python timezone conversion adding minutes to the hour?

So I'm trying to convert a bunch of hours (10:00:00, 14:00:00, etc) from a given timezone to UTC.
When I do so, I keep maddeningly getting things back like "15:51:00".
When you get to that line, and print what value it's using, it's using something like:
1900-01-01 12:00:00-05:51
Which is fine, except for the -05:51 bit. I have no idea why that -05:51 is there, and it's causing me problems. UTC conversion is hour to hour, yes? I think it's got something to do with my timezone conversions, but I really don't get why they would be doing that.
Here's a minimal example that has the same erroneous output; it returns 15:51:00 when it should just return a flat hour, no minutes.
import datetime
from dateutil import tz
jj = datetime.datetime.strptime("10:00:00", "%H:%M:%S")
tzz = tz.gettz('US/Central')
def constructstring(tzz,x):
inter2 = x.replace(tzinfo=tzz) #ERROR HAPPENS HERE (I'm pretty sure anyways)
inter3 = inter2.astimezone(tz.tzutc())
return inter3
print(constructstring(tzz,jj).strftime("%H:%M:%S"))
You are not specifying a date when you create the jj datetime object, so the default date of 1900-01-01 is used. Timezones are not fixed entities; they change over time, and the US/Central timezone used a different offset back in 1900.
At the very least, use a recent date, like today for example:
# use today's date, with the time from jj, and a given timezone.
datetime.datetime.combine(datetime.date.today(), jj.time(), tzinfo=tzz)
If all you need is a time, then don't create datetime objects to store those; the datetime module has a dedicated time() object. I'd also not use strftime() to create objects from literals. Just use the constructor to pass in integers:
jj = datetime.time(10, 0, 0) # or just .time(10)
Other good rules of thumb: If you have to deal with dates with timezones, try to move those to datetime objects in UTC the moment your code receives or loads them. If you only have a time of day, but still need timezone support, attach them to today's date, so you get the right timezone. Only convert to strings again as late as possible.

python schedule to run another file.py every certain time

I have a python script in file called tasks.py containing multiple tasks, processes and functions (and it works perfect to me).
i want to run this file (tasks.py) at certain time ( 1:00 am & 4:45 am & 11:35 am & 6:25 pm & 9:10 pm) every day starting from date say as example 6 aug 2018.
so i created a new file and called it run.py
i used the following code to import tasks.py file
#!/usr/bin/python
import tasks
but i want to schedule this import in the certain times as mentioned above starting from the required date
i tried while function, schedule module, cron module and import os but i failed with all
any body can help please ????
The simple solution can be something like that
import datetime
from time import sleep
rest_seconds = 3600 # sleep for one hour, so the task won't be called few times per hour
while True:
if datetime.datetime.now().hour == 12:
do_task()
sleep(rest_seconds)
If you need a complex one, I use Airflow framework for building scheduled tasks/pipelines

python3 TimeStamp off by 2 hours

I'me a bit new to python but having the hardest time working with timestamps,utc and unixtime.
This example is off by 2 hours:
sec_in_day=86400
today = datetime.datetime.utcnow()
print(today)
two_days_ago=today.timestamp()-(sec_in_day*2);
print("Two days ago (unix)",two_days_ago)
# Convert timestamp via 3rd party
tool:http://www.onlineconversion.com/unix_time.htm
#generated unix-timestamp is 2 hours early according to 3rd party tool
2017-04-11 06:36:49.414133
Two days ago (unix) 1491712609.414133
Converting 1491712609.414133 via online tool gives me
Sun, 09 Apr 2017 04:36:49 GMT
Was expecting Sun, 09 Apr 2017 06:36:49 GMT
This has solved my problem
sec_in_day=86400
today = datetime.datetime.utcnow()
timestamp = today.replace(tzinfo=timezone.utc).timestamp()
print("Today",today)
print("Today-Re", today.replace(tzinfo=timezone.utc))
print("TS",timestamp)
print("TS#2",(timestamp-(sec_in_day*2)))
I believe it all works as designed.
First you do:
today = datetime.datetime.utcnow()
which is in UTC, without daylight-savings adjustment, without local timezone adjustment.
Then you do:
today.timestamp()
Which, according to docs is local time, therefore it includes an adjustment for day-light-savings, as well as local timezone.
This explains the 2 hour difference.
What you might want to look into is today - datetime.timedelta(days=2)
You can also used below code
sec_in_day=86400
today = datetime.datetime.utcnow()
print(today)
two_days_ago=today.timestamp()-(sec_in_day*2);
print("Two days ago (unix): ",datetime.datetime.fromtimestamp(two_days_ago).strftime('%Y-%m-%d %H:%M:%S.%f'))
In this I have used fromtimestamp(two_days_ago).strftime('%Y-%m-%d %H:%M:%S.%f')) function which will convert epoch time into readable form.

Resources