Python程式計算日期、月份和年份(從秒數)
通常,時間以小時、分鐘或秒為單位給出,根據給定的秒數,我們可以計算出天數、月數和年數。Python 中有不同的模組和函式(如 datetime、time 和 divmod())可以幫助我們根據秒數計算日期、月份和年份。
使用 Datatime 模組
Datetime 模組提供用於操作日期和時間的類。此模組提供了各種函式和方法,例如 date、time、datetime、timedelta、minyear、maxyear、UTC 等。
在 datetime 模組的 datetime 方法中,我們有 utcfromtimestamp() 函式,它以秒作為輸入引數,並將秒轉換為年、日期和月份。
語法
使用 utcfromtimestamp() 函式的語法如下。
datetime.datetime.utcfromtimestamp(seconds)
示例
在此示例中,我們將秒數 1706472809 傳遞給 datetime 模組的 utcfromtimestamp(),然後返回年份為 2024、日期為 28 和月份為 1。
import datetime def calculate_date(seconds): date = datetime.datetime.utcfromtimestamp(seconds) year = date.year month = date.month day = date.day return day, month, year seconds = 1706472809 day, month, year = calculate_date(seconds) print("The day, month and year from the given seconds:",day, month, year)
輸出
The day, month and year from the given seconds: 28 1 2024
使用 time 模組
time 模組提供了各種與時間相關的函式,例如 asctime、cloc_gettime 和 gmtime 等。
gmtime() 函式以秒作為輸入引數,並將秒轉換為元組,然後提取年份、日期和月份。
語法
以下是使用 time.gmtime() 函式的語法。
time.gmtime(seconds)
示例
在此示例中,我們將秒數作為輸入引數傳遞給 time 模組的 gmtime() 函式,然後它返回年份、日期和月份的轉換結果。
import time def calculate_date(seconds): time_tuple = time.gmtime(seconds) day = time_tuple.tm_mday month = time_tuple.tm_mon year = time_tuple.tm_year return day, month, year seconds = 1706472809 day, month, year = calculate_date(seconds) print("The day, month and year from the given seconds:",day, month, year)
輸出
The day, month and year from the given seconds: 28 1 2024
使用 divmod() 函式
divmod() 函式以任意兩個實數作為輸入引數,並返回一個包含商和餘數的元組。
語法
以下是 divmod() 函式的語法。
quotient,remainder = divmod(val1,val2)
示例
在此示例中,我們建立一個名為 calculate_name 的函式,它以秒作為輸入引數。在函式中,我們使用 divmod() 函式。年份從 1970 年開始,因此我們必須檢查年份是否為閏年,並生成日期和月份。接下來,它返回日期、月份和年份作為輸出。
def calculate_date(seconds): minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) year = 1970 while days > 365: if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): if days > 366: days -= 366 year += 1 else: break else: days -= 365 year += 1 month_days = [31, 28 + (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] month = 1 while days >= month_days[month - 1]: days -= month_days[month - 1] month += 1 return days + 1, month, year seconds = 1706472809 day, month, year = calculate_date(seconds) print(day, month, year)
輸出
28 1 2024