美文网首页
Python_3_Codecademy_3_Date &

Python_3_Codecademy_3_Date &

作者: 张一闻 | 来源:发表于2016-04-15 03:42 被阅读30次

<a href="http://www.jianshu.com/p/54870e9541fc">总目录</a>


课程页面:https://www.codecademy.com/
内容包含课程笔记和自己的扩展折腾

  1. Import datetime library:
    from datetime import datetime

  2. Get the current date & time
    print datetime.now()
    得到的结果(UTC+01:00)是:2016-04-14 21:04:18.652040

  3. Extract information
    可以从2016-04-14 21:04:18.652040这个时间里获取信息

now = datetime.now()
print now.year # Output: 2016

同理还可以
now.month
now.day
now.hour
now.minute
now.second

  1. 手动调整格式
  • 英国和欧洲都是日/月/年,美国是月/日/年,中国是年/月/日。
  • 有的时候是dd/mm/yyyy, 有的时候又是dd/mm/yy。所以很有手动调整格式的必要。
# 从头开始import library: 
from datetime import datetime
now = datetime.now()
year = now.year 
month = now.month
day = now.day
#
# 作为新手我不是很确定这里variable year的data type, 
# 先问google(或者百度):有check data type的python命令吗?
# 有就直接用。没有就+ strings,没有出现error就是strings。
# 答案是有。所以问python:print type(year), 
# python回答::<type 'int'>。
# 即是integer,year需要转成string才能和其他strings concatenate
#
year_short = str(year)[2] + str(year)[3]
#
# 打印多重格式:
print now
print "%s-%s-%s" % (day, month, year)
print "%s-%s-%s" % (day, month, year_short)
print "%s年%s月%s日" % (year, month, day)
print "%s年%s月%s日" % (year_short, month, day)
"""
Output:
2016-04-14 21:36:02.342821
14-4-2016
14-4-16
2016年4月14日
16年4月14日
"""
# 可是月份不正式,没有04,
# 不过转成string加上0就好了。

相关文章

网友评论

      本文标题:Python_3_Codecademy_3_Date &

      本文链接:https://www.haomeiwen.com/subject/dgfnlttx.html