Python时间模块time、datetime

2017-08-30  本文已影响0人  amuqiao

时间

time模块

time.time()

>>> import time # 导入time模块
>>> time.time() # 返回UTC时间(从1970.1.1到现在的秒数)
1499435147.90761 

time.ctime() 接收一个以秒为单位的实际,然后转换成本地时间的字符串表示

>>> time.ctime() #
'Fri Jul  7 21:46:06 2017'
>>> time.ctime(time.time())
'Fri Jul  7 21:47:18 2017'

格式化时间输出
strftime()

>>> from time import strftime,gmtime
>>> strftime('%Y-%m-%d %H:%M:%S')
'2017-07-07 21:49:47'

gtime() 函数将一个时间戳转换为UTC时区(0时区)的struct_time,可选的参数sec表示从1970-1-1以来的秒数。其默认值为time.time()

>>> strftime('%Y-%m-%d %H:%M:%S',gmtime()) # 
'2017-07-07 13:50:18'

应用1:格式化当前时间,并以字符串的形式输出

>>> import time
>>> create_time = str(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(time.time())))
>>> create_time
'2017-08-29 16:56:36'

datetime模块

>>> from datetime import datetime
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2016-07-21 19:49:15'
>>> datetime.now().isoformat()
'2016-07-21T19:56:46.744893'
>>> str(datetime.now())
'2016-07-21 19:48:37.436886'

python计算明天的日期

from datetime import datetime, timedelta
now = datetime.now()
aDay = timedelta(days=1)
now = now + aDay
print now.strftime('%Y-%m-%d')

python计算上周时间

from datetime import datetime
from datetime import timedelta

now = datetime.now()
aWeek = timedelta(weeks=-1)
now = now + aWeek
print now.strftime('%Y-%m-%d')

使用timedelta可以很方便的在日期上做天days,小时hour,分钟,秒,毫秒,微妙的时间计算,如果要计算月份则需要另外的办法

计算上个月的月份

import time
last_month = time.localtime()[1]-1 or 12
print last_month

timedelta实现日期相减

from datetime import timedelta, datetime
import time

d1 = datetime.now()
time.sleep(10)
eclipseTimes = datetime.now() - d1
print eclipseTimes.total_seconds()  # 转换成miao
上一篇下一篇

猜你喜欢

热点阅读