Python - how to run function at a certain PST/PDT time? - python

I'm beginning to learn python and I've tried to create a script to run a certain command at a certain time. This is what I have so far:
import datetime
day_of_week = datetime.date.today().weekday() # 0 is Monday, 6 is Sunday
time = datetime.datetime.now().time()
if day_of_week == 4 and (time >= datetime.time(2,45) and time < datetime.time(9)):
#do something
elif (day_of_week == 3 and time > datetime.time(22)) or (day_of_week == 4 and time < datetime.time(2,45)):
#wait until 2h45
else:
#do nothing
I want the script to continue only on a certain day and when it's around 19h00 PST/PDT (2h45 GMT/UTC). The one I wrote works fine with GMT/UTC, but I'm certain that it will fail when daylight savings starts or if I change the local timezone to a different one.
What could I do to make the script check for the current time in PST/PDT and continue from there, ignoring or converting the local timezone?

#Ruben, please try this code below. It always look at the time in US/Pacific timezone. Hope it helps. Thanks.
import datetime
import pytz
pst_timezone = pytz.timezone("US/Pacific")
time=datetime.datetime.now(pst_timezone).time()
print(time)
Result: 12:13:10.136603

You should look into pytz
Python: display the time in a different time zone will be helpful too

Pythons Datetime pulls from the system time. So if the system is setup to use DST then you will be fine.
If you don't or cant trust the system time then no build in function will be accurate. You will then need to have your program go out and pull time from another server.

Related

How to compare a datetime object to a certain amount of time?

I am trying to write a program to keep track of the errors. I am storing the first time an error occured and the last time. If the error continues to occur for 45 seconds, I will create an alert but the alert is not the part of my question.
I need to write an if statement to compare 2 datetime objects and take the difference in seconds. Then, if the difference is more than 45 seconds, I will create an alert.
My issue is I couldn't find out how to compare the difference between two datetime objects to a certain amount of time.
All the examples on the web including other StackOverFlow questions are just doing comparisons like if today < yesterday: do something but that doesn't help me because I don't know what will be one side of the comparison.
The time objects I am dealing with are as follows:
errors[oneEquity]['StartTime'] = 12:32:44
errors[oneEquity]['LastTime'] = 12:32:50
I found out from other questions that I can get the difference as follows:
errors[oneEquity]['LastTime'] - errors[oneEquity]['StartTime'] = 0:00:06
I believe that the difference is a datetime object, too. Now, I need to compare that object to 45 seconds but I don't know how to state 45 seconds.
Is it going to be a datetime object? If so, how can I create a datetime object of 45 seconds?
The if-statement I should write is something like that:
if errors[oneEquity]['LastTime'] - errors[oneEquity]['StartTime'] > (45 seconds):
# create an alert
from datetime import datetime
from datetime import timedelta
error_occurs = datetime.now() - timedelta(seconds=45)
# error_occurs = datetime.now() - timedelta(seconds=44)
if datetime.now() - error_occurs >= timedelta(seconds=45):
print('works')
** delta could be constant

How to get the Date and Time of Current Location in Python [duplicate]

This question already has answers here:
How do I get the current time?
(54 answers)
Closed 3 years ago.
I want to get the Date and Time of The Current Location. If somebody runs the code in a different country thought it will show the date and and time for them, and not for me. If you know any commands for this please put the down bellow. I prefer If I don't need a library so that people who get the code don't need to download the library.
I think you can not get the date or time of a location.
This code gets your device's date and time:
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
current_date = now.strftime("%D")
print("Current Time: ", current_time)
print("Current Date: ", current_date)
A standard Python module called datetime can probably help you with retrieving the current system date and time from where the program is run
Since it's a standard module, there would be no need to install it rather just import it in the program itself.
Example :
import datetime
x = datetime.datetime.now()
print(x)
Would give you the output as :
2019-07-20 00:52:27.158746
The above output contains the current year, month, day, hour, minute, second, and microsecond.

Receiving inaccurate time from python time module? [duplicate]

This question already has answers here:
Python: strftime, gmtime not respecting timezone
(2 answers)
Closed 3 years ago.
I am a beginner in programming and I was messing around with the time module in python, as I recently got a raspberry pi and want to start doing some projects. I imported the time module, and just made a loop to print out the time every second. The code runs correctly, but the time given is not accurate to my location. Currently, it is the 14th and a Friday, around 9 pm, but it is returning the 15th a Saturday, with 0 hours and 10 minutes. Does anyone know how I can obtain the correct time?
I tried a couple of the different functions to receive the current time like .localtime() and .gmtime() but they're all the same.
import time
while(True):
thisTime = time.gmtime()
print(time.asctime(thisTime))
time.sleep(1)
Go ahead and check out this post, I think this is your solution:
Python get current time in right timezone
So assuming your computer's time is configured correctly, you could use this:
from datetime import datetime
naive_dt = datetime.now()
It's unclear what else you've tried, although the following should work:
localtime = time.localtime()
print(time.asctime(localtime))
↳ https://docs.python.org/3/library/time.html#time.localtime

Python datetime subtracting date oddity

I have a datetime object created from which I subtract 13 days as follow:
(date.today()-timedelta(days=13)).strftime('%Y-%m-%d')
The strangeness occurs when I execute the code at 6AM and 8:30AM. At 6AM, the resulting string is returned as (if today is 2012-02-29):
2012-02-15
which is 14 days before the current! However, running the same line at 8:30AM, the resulting string is returned as:
2012-02-16
Which then correct. So far I have not been able to figure out what the difference is between the small period of time. I use timezone naive datetime objects, if that is important. I would like to know what could cause this change in the resulting string date.
Many thanks.
EDIT: (based on eumiro's suggestion below)
datetime.datetime.now() returns:
>>> datetime.datetime(2012, 2, 29, 10, 46, 20, 659862)
And the timezone is Europe/Vienna on the server and in the django application that runs the line of code.
I also tried running a similar line to the one you suggested:
(pytz.timezone(settings.TIME_ZONE).localize(datetime.now(), is_dst=True) - \
timedelta(days=13)).strftime('%Y-%m-%d')
But with the same results... which is why I think I don't think it has much to do with timezones also. But at the same time not sure where else to look.
You live somewhere in America? This is the place where the timezones are around 6-8 hours behind the UTC and that's the time of UTC midnight.
What does datetime.datetime.now() return?
If you want to get the real local time, use this (replace "America/New_York" with your timezone):
from datetime import datetime, timedelta
import pytz
now = datetime.datetime.now(pytz.timezone("America/New_York"))
dt = (now - timedelta(days=13)).strftime('%Y-%m-%d')
and it should return the same correct values from midnight until midnight.
Unfortunately DST is poorly supported in Python.
Even pytz is not perfect, but can be made to work with hacks.
You have to decide what it means to subtract 2 days from 10th, 1p.m., either 2 calendar days or 48 hours or 172800 seconds.

Python - Trying to get a different timezone

Totally new to python, I'm actually working on an ex-colleague's script. in looking at it it seems fairly straight-forward. Here's the situation:
The script looks at current localtime (UTC) and renders a time-based table that scrolls/changes throughout the day as the hours pass so there's always a rolling 8 hour table.
The problem is that now we'd like to deploy a copy of this tool (on the same server) in CST ('America/Chicago') (meaning I need to change the UTC time to CST) so I'm just trying to find a way to modify what he has to make the 'current_time' variable == GMT -6.
He used strftime() to get the first hour:
current_time = int(strftime("%H"))
if current_time <19:
temp_page.write(...)
elif current_time == 19:
temp_page.write(...)
etc.
So - from my php knowledge, I'd love to be able to do something like:
current_time = int(strftime("%H"), (localtime() -6 hours))
(yes, I realize that's not real php code, but hopefully you get my meaning ;-))
In my research, I've come across pytz, but this is not installed on the webserver, though I can probably get it if that's the best/easiest way too implement it.
Any help is greatly appreciated.
Yes, try to install pytz, it will help you a lot when working with different timezones (and UTC).
The current UTC time (independent from the timezone of your computer) can be obtained with:
import pytz
from datetime import datetime
now = datetime.now(pytz.utc)
now is now datetime.datetime(2011, 11, 30, 14, 26, 30, 628014, tzinfo=<UTC>) and you can use it to calculate the current UTC hour with now.hour (returns 14)
You could probably use the datetime module (it's part of the standard library, so it's installed if a standard python is on the system).
In particular, datetime objects can have an optional tzinfo attribute, used during timezone conversions. Here's a blog post that explains step-by-step how to use those.

Categories