skip to Main Content

I have a background task that I want to schedule to run once the NYSE is closed.
My background scheduler (redis-rq) requires the time will be in UTC and I’m using python.
The task is scheduled during the trading day, so it means that I can’t use offset or specific dates because it can be called dynamically.

So, what I just want is that once a trigger is called, I want to schedule the task to run at the end of the current trading day, which again is 16:00 EST time.

I’ve tried several options like getting the time in EST with:

datetime.time(16, 0, tzinfo=pytz.timezone('US/Eastern'))

But I can’t figure out how to convert it to UTC, I tried stuff like .replace() with no success.

Thanks in advance.

2

Answers


  1. You can use today’s date, combine with the desired NY time, set the time zone to New York (US Eastern), then convert to UTC:

    from datetime import date, datetime, time
    from zoneinfo import ZoneInfo # Python 3.9
    
    t_utc = (
        datetime.combine(
            date.today(),
            time(16,0),
        )
        .replace(tzinfo=ZoneInfo("America/New_York"))
        .astimezone(ZoneInfo("UTC"))
    )
    
    print(t_utc)
    2023-05-10 20:00:00+00:00
    

    Note on time zone handling:

    • with the deprecated pytz you cannot replace the tzinfo, use e.g. pytz.timezone("America/New_York").localize(... instead
    • for zoneinfo to work properly on Windows, make sure to have tzdata package installed and up-to-date
    Login or Signup to reply.
  2. Try to use pytz library: https://pypi.org/project/pytz/ .

    The code with this library can solve your task:

    import pytz
    from datetime import datetime, time
    
    nyse_close_time_et = time(16, 0)
    now_et = datetime.now(pytz.timezone('US/Eastern'))
    nyse_close_datetime_et = datetime.combine(now_et.date(), nyse_close_time_et)
    nyse_close_datetime_utc = nyse_close_datetime_et.astimezone(pytz.utc)
    print(nyse_close_datetime_utc)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search