经常获得了一个用户提交的当前日期,我们需要以这个日期为依据返回它的前一天、后一天的日期或者转换操作等。用Python可以非常简单的解决这些关于日期计算的问题不管何时何地,只要我们编程时遇到了跟时间有关的问题,都要想到 datetime 和 time 标准库模块,今天我们就用它内部的方法,详解python操作日期和时间的方法。
数据库的datetime格式转换成字符串datetime > > > strftime > > > string 字符串转换成数据库的datetimestring > > > strptime > > > datetime
将字符串的时间转换为时间戳 1 2 3 4 5 6 7 a = "2016-04-16 22:36:54" import timetimeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S" ) timeStamp = int(time.mktime(timeArray)) timeStamp == 1460817414
格式更改 如 a = “2016-04-16 22:36:54”,想改为 a = “2016/04/16 22:36:54”
1 2 3 timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S" ) otherStyleTime = time.strftime("%Y/%m/%d %H:%M:%S" , timeArray)
时间戳转换为指定格式日期 方法一 1 2 3 4 5 利用localtime()转换为时间数组,然后格式化为需要的格式,如: timeStamp = 1460817414 timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S" , timeArray) otherStyletime == "2016-04-16 22:36:54"
方法二 1 2 3 4 5 import datetimetimeStamp = 1460817414 dateArray = datetime.datetime.utcfromtimestamp(timeStamp) otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S" ) otherStyletime == "2016-04-16 22:36:54"
获取当前时间并转换为指定日期格式 方法一 1 2 3 4 5 6 import timenow = int(time.time()) timeArray = time.localtime(timeStamp) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S" , timeArray)
方法二 1 2 3 4 5 import datetimenow = datetime.datetime.now() otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S" )
获得三天前的时间的方法 1 2 3 4 5 6 7 8 import timeimport datetimethreeDayAgo = (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,microseconds
给定时间戳,计算该时间的几天前时间 1 2 3 4 5 6 timeStamp = 1460817414 import datetimeimport timedateArray = datetime.datetime.utcfromtimestamp(timeStamp) threeDayAgo = dateArray - datetime.timedelta(days = 3 )
注:参考获得三天前的时间的方法,可以转换为其他的任意格式了
用Python计算昨天和明天的日期 1 2 3 4 5 6 7 8 9 10 11 12 >>> import datetime >>> today = datetime.date.today() >>> print today 2016 -04 -16 >>> yesterday = today - datetime.timedelta(days=1 ) >>> print yesterday2016 -04 -15 >>> tomorrow = today + datetime.timedelta(days=1 ) >>> print tomorrow2016 -04 -17 >>> print "昨天:%s, 今天:%s, 明天:%s" % (yesterday, today, tomorrow) >>>昨天:2016 -04 -15 , 今天:2016 -04 -16 , 明天:2016 -04 -17
python里使用time模块来获取当前的时间 1 2 3 4 5 6 7 8 import timeprint (time.strftime("%H:%M:%S" ))print (time.strftime("%I:%M:%S" ))
打印出当前的日期的python程序 1 2 3 4 5 6 import timeprint (time.strftime("%d/%m/%Y" ))16 /04 /2016
使用datetime模块来获取当前的日期和时间 1 2 3 4 5 6 7 8 9 10 11 12 import 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)
文章参考资料 python操作日期和时间的方法
<
卸载 Mysql
Python 时间类型
>