I tried to make a function to judge whether the major stock exchanges in the world are daylight saving time with python

*Fixed

--2016.12.12
4. Corrected the def argument set to date = datetime.datetime.today () in the script.
If this is the case, the default will be the time when def was loaded once. Because it becomes.

1. Motivation

――It is tedious to manually switch and judge whether the world's major stock exchanges are this summer time. Can it be automated?
――I'm trying to find out more about the time zone. -Although it is mostly explained in [Python] Convert time zone, I wonder if you can make it a check function so that you do not have to worry every time.

2. Environment

--python3.x (probably 2.7 is ok)
--Required packages -pytz

3. Check method.

--Pytz's dst (summer time? Is like Japanese English, like daylight saving time) is 0 to determine whether it is daylight saving time. ――Do you set the date and time to judge daylight saving time in local time? Is it judged by Japan time? Is a point of concern, so I can check either one. --Since the time when switching daylight saving time (time) is delicate, please refer to "5. Precautions for checking daylight saving time". ――The summer time can be checked in the United States (New York), United Kingdom (London), Canada (Toronto), Brazil (Sao Paulo), Australia (Sydney), Germany (Frankfurt * Frankfurt, Hessen), so Berlin ), But I think we can handle it anywhere by adding a time zone.

4. Script

You can check it by embedding the following script.

--calcdifftime: Time difference from the specified time zone of the specified time (Japan if not specified) This must be necessary. --checkdst: Checks whether the time zone of the designated securities company is daylight saving time at the specified time (specified time zone (Japan if not specified))

Please refer to 5. Verification for specific usage.

import pytz ,datetime

#Add from here if necessary.
tzUTC = pytz.timezone("UTC")                  #Standard time
tzNYC = pytz.timezone("America/New_York")     #USA(New York)
tzTYO = pytz.timezone("Asia/Tokyo")           #Japan(Tokyo)
tzLON = pytz.timezone("Europe/London")        #England(London)
tzYTO = pytz.timezone("America/Toronto")      #Canada(Toronto)
tzSAO = pytz.timezone("America/Sao_Paulo")    #Brazil(Sao paulo)
tzSYD = pytz.timezone("Australia/Sydney")     #Australia(Sydney)
tzFRA = pytz.timezone("Europe/Berlin")        #Germany(Frankfurt) *Frankfurt、ヘッセン州がなかったのでベルリン
#So far

def calcdifftime(tz = tzNYC, date = -1,tzbase = -1):
        """
        [param]
        tz : checked pytz.timezone
        date:checked datetime
        tzbase:bassis pytz.timezone

        [return]
        float:different hours
        """
        if(date==-1):
                date =  datetime.datetime.today() 
        if(tzbase==-1):
                tzbase = tzTYO
        tabse   = tzbase.localize(date)
        tztime = tz.localize(date)
        diff = tabse - tztime
        diff_hours = diff.total_seconds()/3600
        return(diff_hours)

def checkdst(tz = tzNYC, date=-1,tzbase=-1):
        """
        [param]
        tz : checked pytz.timezone
        date:checked datetime
        tzbase:bassis pytz.timezone

        [return]
        bool: True:dst , False:std
        """
        if(date==-1):
                date =  datetime.datetime.today() 
        if(tzbase==-1):
                tzbase = tzTYO
        tbase = tzbase.localize(date)
        chgdate = tbase.astimezone(tz)
        #print(chgdate)
        if(chgdate.dst().seconds !=0):
                return(True)
        else:
                return(False)

5. Verification

For the time being, we are checking the start and end times of daylight saving time in the United States (US) in Japan time and local time.

def tztest(t,tz,tzbase = -1):
        diff = calcdifftime(tz,t) #Time difference with Japan
        if(tzbase ==  -1): #When tzbase is not specified(In Japan time)Operation test
                if(checkdst(tz,t)):
                        st = "daylight saving time"
                else:
                        st = "standard time"
        elif(checkdst(tz,t,tzbase)): #Test when tzbase is specified (for basic local time)
                st = "daylight saving time"
        else:
                st = "standard time"
        if(tzbase == -1):
                tzbasename = tzTYO.zone
        else:
                tzbasename = tzbase.zone
        print("Check time ",t,tzbasename)
        print("tz name".ljust(20),"Time diff".ljust(10),"DST STD")
        print(tz.zone.ljust(20),str(diff).ljust(10),st)

print("Check in Japan time")
#US (US) Daylight Saving Time Check
#Check time  2016-03-13 16:00:00 Asia/Tokyo
#tz name              Time diff  DST STD
#America/New_York     -13.0      daylight saving time
t = datetime.datetime(2016, 3, 13, 16, 0)
tztest(t,tzNYC)

#Normal check in the United States (US)
#Check time  2016-11-06 15:00:00 Asia/Tokyo
#tz name              Time diff  DST STD
#America/New_York     -14.0      standard time
t = datetime.datetime(2016, 11, 6, 15, 0)
tztest(t,tzNYC)

print("Check in local time")
#US (US) Daylight Saving Time Check
#Check time  2016-03-13 03:00:00 America/New_York
#tz name              Time diff  DST STD
#America/New_York     -13.0      daylight saving time
t = datetime.datetime(2016, 3, 13, 3, 0)
tztest(t,tzNYC,tzNYC)

#Normal check in the United States (US)
#Check time  2016-11-06 01:00:00 America/New_York
#tz name              Time diff  DST STD
#America/New_York     -14.0      standard time
t = datetime.datetime(2016, 11, 6, 1, 0)
tztest(t,tzNYC,tzNYC)

6. Precautions for daylight saving time check

――The daylight saving time in the United States (US) changes at 2:00 on March 13, 2016, so what about daylight saving time from here? However, please note that it will be possible to judge daylight saving time at 3:00 (one hour ahead) on March 13, 2016, when it actually started.
It will return to standard time at 2:00 on November 6, 2016, but it seems that daylight saving time can be judged until 1:00 on November 6, 2016 (one hour back). (1 o'clock on November 6, 2016 is judged to be standard time)
――Since Germany and other countries are similar, it seems that you need to be careful about the time to check.
――Strictly speaking, there are some strange (uncheckable) times, but you may not have to worry about the start and end times of daylight saving time because the market is closed at midnight on Sunday. However, be careful when checking once a week (such as Sunday).

7. Other

――This time, I referred to the name of a certain city of a securities company in each country. What should you do with the abbreviation? Appropriate? ?? I used the abbreviation for the local city, but at that time, the city / airport code might be cheaper to use. I am referring to it.

8. Sites that I mainly referred to this time

-[Python] Convert Time Zone -[[python] Time zone list in pytz module](http://komaken.me/blog/2013/02/15/pythonpytz%E3%83%A2%E3%82%B8%E3%83%A5% E3% 83% BC% E3% 83% AB% E3% 81% A7% E3% 81% AE% E3% 82% BF% E3% 82% A4% E3% 83% A0% E3% 82% BE% E3% 83% BC% E3% 83% B3% E4% B8% 80% E8% A6% A7 /) -[List of Stock Exchanges](https://ja.wikipedia.org/wiki/%E8%A8%BC%E5%88%B8%E5%8F%96%E5%BC%95%E6%89% 80% E3% 81% AE% E4% B8% 80% E8% A6% A7) -City / Airport Code Search

Recommended Posts

I tried to make a function to judge whether the major stock exchanges in the world are daylight saving time with python
I also tried to imitate the function monad and State monad with a generator in Python
I tried to implement the mail sending function in Python
I tried to make a stopwatch using tkinter in python
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
[5th] I tried to make a certain authenticator-like tool with python
I tried to describe the traffic in real time with WebSocket
[2nd] I tried to make a certain authenticator-like tool with python
I tried to make a regular expression of "time" using Python
[3rd] I tried to make a certain authenticator-like tool with python
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
I tried to make an image similarity function with Python + OpenCV
I tried to find out the difference between A + = B and A = A + B in Python, so make a note
A story that didn't work when I tried to log in with the Python requests module
Python: I tried to make a flat / flat_map just right with a generator
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
Python: I want to measure the processing time of a function neatly
I want to make a game with Python
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I tried to make a simple mail sending application with tkinter of Python
[Patent analysis] I tried to make a patent map with Python without spending money
[Python] Smasher tried to make the video loading process a function using a generator
[Python] I tried to get the type name as a string from the type function
[Python & SQLite] I tried to analyze the expected value of a race with horses in the 1x win range ①
Introduction to AI creation with Python! Part 2 I tried to predict the house price in Boston with a neural network
I tried to learn the sin function with chainer
I tried to graph the packages installed in Python
I tried to touch the CSV file with Python
I tried to draw a route map with Python
I tried to solve the soma cube with python
I tried to implement a pseudo pachislot in Python
I want to work with a robot in python.
I tried to automatically generate a password with Python3
I tried to solve the problem with Python Vol.1
[LPIC 101] I tried to summarize the command options that are easy to make a mistake
I tried to make something like a chatbot with the Seq2Seq model of TensorFlow
I tried to make a real-time sound source separation mock with Python machine learning
How to unit test a function containing the current time using freezegun in python
I wanted to create a dll to use a function written in C from Python with ctypes, but I had a hard time
I tried to make a function to retrieve data from database column by column using sql with sqlite3 of python [sqlite3, sql, pandas]
(Python: OpenCV) I tried to output a value indicating the distance between regions while binarizing the video in real time.
I tried to find the entropy of the image with python
A super introduction to Django by Python beginners! Part 6 I tried to implement the login function
I tried to simulate how the infection spreads with Python
I tried to summarize what python strong people are doing in the competition professional neighborhood
I tried to make various "dummy data" with Python faker
I tried to implement a one-dimensional cellular automaton in Python
[1 hour challenge] I tried to make a fortune-telling site that is too suitable with Python
How to write offline real time I tried to solve the problem of F02 with Python
I made a package to filter time series with python
[Python] I want to make a 3D scatter plot of the epicenter with Cartopy + Matplotlib!
I made a class to get the analysis result by MeCab in ndarray with python
I tried "How to get a method decorated in Python"
I tried to illustrate the time and time in C language
I tried to make a generator that generates a C # container class from CSV with Python
I tried to create a Python script to get the value of a cell in Microsoft Excel
I tried to make GUI tic-tac-toe with Python and Tkinter