Python日期时间time模块,datetime模块

time模块获取当前时间戳

import time
now = time.time()
print '当前时间戳为',now

 

time模块获取当前时间格式化

import time
now = time.strftime("%Y-%m-%d %H:%M:%S")
print "当前时间格式化输出", now

print time.strftime("%Y-%m-%d %X")  # 第二种方式

print time.strftime("%Y%m%d%H%M%S",time.localtime(time.time())) # 第三种方式

 

time模块将时间戳格式化输出

import time
now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(1481248540.68))
print "1481248540.68 格式化输出结果为",now

 

time模块将格式化的日期转为时间戳

import time
now = time.mktime(time.strptime('2016-11-18 23:59:03','%Y-%m-%d %H:%M:%S'))
print "转化后的时间戳为",now

 

获取现行时间 datetime模块

import datetime
now = datetime.datetime.now()
print "现在的时间是",now

 

获取日期时间详细信息

import datetime
now = datetime.datetime.now()
print now.date()  #获取日期
print now.time()  #获取时间
print now.year   #获取年份
print now.month  #获取月份
print now.day    #获取天数
print now.hour   #获取小时
print now.minute #获取分钟
print now.second #获取秒数
print now.weekday() #返回星期几

 

将字符串转化为datetime

import datetime
mytime =  datetime.datetime.strptime("2016-12-23 23:00:02","%Y-%m-%d %H:%M:%S")
print mytime
print type(mytime)

 

posted @ 2017-10-20 17:58  王哈哈-就很棒  阅读(469)  评论(0)    收藏  举报