引入函数包
from datetime improt datetime
from datetime import datetime
now = datetime.now()
print now
其中now用来存储现在的日期
该语句打印出:
2013-11-04 23:37:41.241000
继续使用now完成输出:
from datetime import datetime
now=datetime.now()
print now
print now.year
print now.month
print now.day
实际上,还可输出now的更多的东西
如果我想要输入的格式为yyyy/mm/dd该怎么办呢?
from datetime import datetime
now=datetime.now()
print now
print now.year
print now.month
print now.day
"""尝试下列三种方法"""
print now.year,"/",now.month,"/",now.day
print now.year+now.month+now.day
print str(now.year)+"/"+str(now.month)+"/"+str(now.day)
最终三者的输出结果是:
2013 / 11 /4
2028
2013/11/4
第一种方法含有空格,第二种方法是直接把他们按照整形来进行加法,第三种方法str()把整形转换为字符型来输出.(Python中三种数据类型,int、float、string)
针对时间同样:
from datetime import datetime
now = datetime.now()
print str(now.hour)+":"+str(now.minute)+":"+str(now.second)
因此,输出当地时间完整代码(时间格式:dd/mm/yyyy hh:mm:ss):
from datetime import datetime
now = datetime.now()
print str(now.day)+"/"+str(now.month)+"/"+str(now.year)+" "+str(now.hour)+":"+str(now.minute)+":"+str(now.second)
输出:
4/11/2013 23:50:10