--- title: Python 時間模組 特定時間執行 tags: Python, time description: Python 使用時間模組於特定時間內執行程式 --- # 在指定時間執行搶票 <!-- Put the link to this slide here so people can follow --> slide: https://hackmd.io/@xx78826/python-on-time-buy-ticket ## Who am I? - 一位會寫簡單爬蟲的肥宅 --- 使用情境是什麼情況下呢? 搶票情境當過了24:00時開放新的預約,所以需要再24:00時執行搶票的預約? 小提醒如果想在 2022/9/3 凌晨12:00搶票 其實真正的時間是 2022/9/4 00:00執行程式 關於時間模組的4個步驟 1.現在時間datetime ``` import datetime x = datetime.datetime.now() ``` output 2022-09-03 19:14:08.982975 2.時間字串 strftime ``` x_strftime = x.strftime("%Y-%m-%d %H:%M:%S") print(x_strftime) ``` output 2022-09-03 17:37:08 3.時間元組 strptime ``` x_strptime = time.strptime(x_strftime, "%Y-%m-%d %H:%M:%S") print(x_strptime) ``` output time.struct_time(tm_year=2022, tm_mon=9, tm_mday=3, tm_hour=17, tm_min=37, tm_sec=8, tm_wday=5, tm_yday=246, tm_isdst=-1) 4.時間數值 time.mktime() ``` time.mktime(x_strptime) ``` output 1662197828.0 **時間數值起始時間為1970年1月1日0點0分0秒** 把目標時間和現在時間,皆變成時間數值後則可以做判斷。 --- ### 進入正題;如何在一個指定時間,執行一段程式碼呢? ``` if 目標時間 > 現在時間: print("執行") while 目標時間 > 現在時間: time.sleep(0.5) else: print("時間到開始執行這裡") ``` 當目標時間還大於現在時間時,程式碼會進行time.sleep(0.5)等待0.5秒, 當時間到了執行時間,則開始執行else的部分;也就是開始進行搶票的動作。 這是我想到的等待時間到達後,則執行搶票的方法,不知道有更好的方法? --- 參考資料來源 有幫助我在定時執行程式上的網誌 https://officeguide.cc/python-time-tutorial-examples/ 有幫助我在定時執行程式上的 時 分 秒 https://ithelp.ithome.com.tw/articles/10235251
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up