0

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?

  • 3
    Why are you trying to do this in Python instead of using the functionality built into the OS (cron on *nix, Task Scheduler on Windows), both of which would do the work adjusting for DST for you? – Ken White Feb 02 '18 at 19:39
  • I don't want to run this on a scheduled basis. I want to open the script when I need it. I'm going to send this to a friend and the restriction on a single day is to avoid running the script when it's not supposed to. – Ruben Salvado Feb 02 '18 at 19:43

3 Answers3

0

You should look into pytz

Python: display the time in a different time zone will be helpful too

ExtractTable.com
  • 762
  • 10
  • 20
0

@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
jose_bacoy
  • 12,227
  • 1
  • 20
  • 38
-1

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.

Chad G
  • 135
  • 8