Python 时间相关 - zhongjiajie/zhongjiajie.github.com GitHub Wiki
How do I calculate the date six months from the current date using the datetime Python module
from datetime import datetime, timedelta
# 今天日期
now = datetime.now().strftime('%Y%m%d')
# 两天后日期
delta = timedelta(days=2)
two_day_after = datetime.now() + delta
# 六个月前日期
delta = timedelta(6 * 365 / 12)
six_month_ago = datetime.now() + delta
- 通过
dateutil.relativedelta
实现加减这里
import datetime
import dateutil.relativedelta
d = datetime.datetime.strptime("2013-03-31", "%Y-%m-%d")
d2 = d - dateutil.relativedelta.relativedelta(months=1)
print(d2)
将时间中的某个部分其换成指定的时间详情看这里
from datetime import datetime
now = datetime.now()
sepcial_time = now.replace(hour=12, minute=00)
import datetime
print(datetime.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))
from datetime import datetime
from pytz import timezone
# 获取指定时区的当前时间
tz_self = timezone('Asia/Shanghai')
datetime.now(tz=tz_self)
# 获取指定时区的指定时间
datetime(2018, 1, 1, tzinfo=tz_self)
# 获UTC当前时间
datetime.utcnow()
import timeit
def timeit_add(a, b):
return a + b
a = 1
b = 3
timeit.timeit('"-".join([str(n) for n in range(100)])', number = 10000)
timeit.timeit('def timeit_add(a, b): return a + b; timeit_add(1 ,3)', number = 10000)