1.将字符串的时间转换为时间戳
方法:a = "2013-10-10 23:40:00"#将其转换为时间数组import timetimeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")#转换为时间戳:timeStamp = int(time.mktime(timeArray))timeStamp == 13814196002.格式更改如a = "2013-10-10 23:40:00",想改为 a = "2013/10/10 23:40:00"方法:先转换为时间数组,然后转换为其他格式复制代码代码如下:timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)3.时间戳转换为指定格式日期方法一:利用localtime()转换为时间数组,然后格式化为需要的格式,如:复制代码代码如下:timeStamp = 1381419600timeArray = time.localtime(timeStamp)otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)otherStyletime == "2013-10-10 23:40:00"方法二:import datetimetimeStamp = 1381419600dateArray = datetime.datetime.utcfromtimestamp(timeStamp)otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")otherStyletime == "2013-10-10 23:40:00"4.获取当前时间并转换为指定日期格式方法一:import time#获得当前时间时间戳now = int(time.time()) ->这是时间戳#转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"timeArray = time.localtime(timeStamp)otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)方法二:import datetime#获得当前时间now = datetime.datetime.now() ->这是时间数组格式#转换为指定的格式:otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")5.获得三天前的时间的方法import timeimport datetime#先获得时间数组格式的日期threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))#转换为时间戳:timeStamp = int(time.mktime(threeDayAgo.timetuple()))#转换为其他字符串格式:otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")注:timedelta()的参数有:days,hours,seconds,microseconds6.给定时间戳,计算该时间的几天前时间timeStamp = 1381419600#先转换为datetimeimport datetimeimport timedateArray = datetime.datetime.utcfromtimestamp(timeStamp)threeDayAgo = dateArray - datetime.timedelta(days = 3)#参考5,可以转换为其他的任意格式了7、用Python计算昨天和明天的日期>>> import datetime #导入日期时间模块>>> today = datetime.date.today() #获得今天的日期>>> print today #输出今天日期2014-01-04 >>> yesterday = today - datetime.timedelta(days=1) #用今天日期减掉时间差,参数为1天,获得昨天的日期>>> print yesterday2014-01-03 >>> tomorrow = today + datetime.timedelta(days=1) #用今天日期加上时间差,参数为1天,获得明天的日期>>> print tomorrow2014-01-05 >>>>>> print "昨天:%s, 今天:%s, 明天:%s" % (yesterday, today, tomorrow) #字符串拼接在一起输出,这3天的日期昨天:2014-01-03, 今天:2014-01-04, 明天:2014-01-058、python里使用time模块来获取当前的时间#!/usr/bin/pythonimport timeprint (time.strftime("%H:%M:%S"))## 12 hour format ##print (time.strftime("%I:%M:%S"))#:输出#18:11:30#6:11:309、打印出当前的日期的python程序!/usr/bin/pythonimport time## dd/mm/yyyy格式print (time.strftime("%d/%m/%Y"))#输出:11/03/201410、使用datetime模块来获取当前的日期和时间#!/usr/bin/pythonimport datetimei = datetime.datetime.now()print ("当前的日期和时间是 %s" % i)print ("ISO格式的日期和时间是 %s" % i.isoformat() )print ("当前的年份是 %s" %i.year)print ("当前的月份是 %s" %i.month)print ("当前的日期是 %s" %i.day)print ("dd/mm/yyyy 格式是 %s/%s/%s" % (i.day, i.month, i.year) )print ("当前小时是 %s" %i.hour)print ("当前分钟是 %s" %i.minute)print ("当前秒是 %s" %i.second)