本節介紹python中的時間模組time和日期模組datetime,這兩個模組非常重要。datetime提供了更高階的用法,因此在大多數的場景下都應該選擇用datetime,而不是time。
import time
# get current timestamp
print(time.time())
# construct a struct_time object
t = time.localtime(1599094704.0659297)
print(t)
# convert struct_time to string
t_str = time.strftime("%y-%m-%d %h:%m:%s", t)
print(t_str)
# convert string to struct_time
t = time.mktime(time.strptime('2020-09-03 08:58:24', '%y-%m-%d %h:%m:%s'))
# minus
t1 = time.time()
time.sleep(2)
t2 = time.time()
print(t2 - t1)
執行結果:
d:\work\python_workspace\python_study\venv\scripts\python.exe d:/work/python_workspace/python_study/basic_12/test_time.py
1599125762.2383406
time.struct_time(tm_year=2020, tm_mon=9, tm_mday=3, tm_hour=8, tm_min=58, tm_sec=24, tm_wday=3, tm_yday=247, tm_isdst=0)
2020-09-03 08:58:24
2.0001144409179688
process finished with exit code 0
import datetime
import time
# get current timestamp
time_stamp = datetime.datetime.now().timestamp()
print(time_stamp)
# construct a datetime object
t = datetime.datetime.fromtimestamp(time_stamp)
print(t)
# convert datetime to string
t_str = datetime.datetime.now().strftime("%y-%m-%d %h:%m:%s.%f")
print(t_str)
# convert string to datetime
t = datetime.datetime.strptime("2020-09-03 09:32:00.792264", "%y-%m-%d %h:%m:%s.%f")
print(t)
# minus
t1 = datetime.datetime.now()
time.sleep(2)
t2 = datetime.datetime.now()
print(t2 - t1)
執行結果:
d:\work\python_workspace\python_study\venv\scripts\python.exe d:/work/python_workspace/python_study/basic_12/test_datetime.py
1599125850.274376
2020-09-03 17:37:30.274376
2020-09-03 17:37:30.274376
2020-09-03 09:32:00.792264
0:00:02.000115
process finished with exit code 0
python之時間日期calendar
calendar是與日曆相關的模組,calendar模組檔案裡定義了很多態別,主要有calendar,textcalendar以及htmlcalendar型別。其中,calendar是textcalendar與htmlcalendar的基類。該模組檔案還對外提供了很多方法,例如 calendar,m...
SQL學習之時間日期函式
菜鳥教程 函式描述now 返回當前的日期和時間 curdate 返回當前的日期 curtime 返回當前的時間 date 提取日期或日期 時間表示式的日期部分 extract 返回日期 時間的單獨部分 date add 向日期新增指定的時間間隔 date sub 從日期減去指定的時間間隔 dated...
Linux之時間日期類命令
date顯示當前時間 1 基本語法 注意命令與引數之間有空格 a date 功能描述 顯示當前時間 b date y 功能描述 顯示當前年份 c date m 功能描述 顯示當前月份 d date d 功能描述 顯示當前是哪一天 e date y m d 功能描述 顯示當前年月日各種格式 f dat...