python-datetime

字符串,时间转换

# 字符串转时间
lastTradeDate = datetime.datetime.strptime("20180226152134", '%Y%m%d%H%M%S')

# 时间转字符串
endDateStr = endDate.strftime('%Y%m%d') # 结果显示:'20171007'

只要日期,去掉时分秒

today = datetime.date(2020,1,1)

获取星期

d.weekday()
#0代表周日
date.weekday()
# Return the day of the week as an integer, where Monday is 0 and Sunday is 6. For example, date(2002, 12, 4).weekday() == 2, a Wednesday. See also isoweekday().

获取当前时间

# 当前日期
today = datetime.date.today()

datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# 毫秒
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

日期加减

startDate = code['list_date']
endDate = startDate + datetime.timedelta(days=365)

两个日期相差多少天。

d1 = datetime.datetime.strptime('2012-03-05 17:41:20', '%Y-%m-%d %H:%M:%S')
d2 = datetime.datetime.strptime('2012-03-02 17:41:20', '%Y-%m-%d %H:%M:%S')
delta = d1 - d2
print delta.days

sleep

#!/usr/bin/python
import time

print "Start : %s" % time.ctime()
# 单位 s
time.sleep( 5 )
print "End : %s" % time.ctime()

# 0.5s
time.sleep( 0.5 )

计算函数时间


import time

start = time.perf_counter()

....

delta = time.perf_counter() - start
print("程序运行的时间是:{}秒".format(delta))



# Start the stopwatch / counter
t1_start = time.process_time()

datas = dbService.get_data(count, 'd')

# Stop the stopwatch / counter
t1_stop = time.process_time()
print("Elapsed time during the whole program in seconds:",
t1_stop - t1_start)

import time

print('我是time()方法:{}'.format(time.time()))
print('我是perf_counter()方法:{}'.format(time.perf_counter()))
print('我是process_time()方法:{}'.format(time.process_time()))
t0 = time.time()
c0 = time.perf_counter()
p0 = time.process_time()
r = 0
for i in range(10000000):
r += i
time.sleep(2)
print(r)
t1 = time.time()
c1 = time.perf_counter()
p1 = time.process_time()
spend1 = t1 - t0
spend2 = c1 - c0
spend3 = p1 - p0
print("time()方法用时:{}s".format(spend1))
print("perf_counter()用时:{}s".format(spend2))
print("process_time()用时:{}s".format(spend3))
print("测试完毕")

纳秒统计

# Start the stopwatch / counter 
t1_start = time.process_time_ns()

for i in range(n):
print(i, end =' ')

print()

# Stop the stopwatch / counter
t1_stop = time.process_time_ns()

print(f"用时:{(t1_stop - t1_start) / 60} 纳秒")