【Python基础】日期和时间


Python 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。

Python 提供了一个 time calendar 模块可以用于格式化日期和时间。

时间间隔是以秒为单位的浮点小数。

每个时间戳都以自从 1970 1 1 日午夜(历元)经过了多长时间来表示。

Python time 模块下有很多函数可以转换常见日期格式。如函数 time.time() 用于获取当前时间戳 , 如下实例 :

#!/usr/bin/python# -*- coding: UTF-8 -*-import time;  # 引入 time 模块 ticks = time.time()print " 当前时间戳为 :", ticks

以上实例输出结果:

当前时间戳为 : 1459994552.51

时间戳单位最适于做日期运算。但是 1970 年之前的日期就无法以此表示了。太遥远的日期也不行, UNIX Windows 只支持到 2038 年。

 

获取当前时间

从返回浮点数的时间辍方式向时间元组转换,只要将浮点数传递给如 localtime 之类的函数。


#!/usr/bin/python# -*- coding: UTF-8 -*-import time
localtime = time.localtime(time.time())print "本地时间为 :", localtime

以上实例输出结果:


本地时间为
 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)

 

获取格式化的时间

你可以根据需求选取各种格式,但是最简单的获取可读的时间模式的函数是 asctime():


#!/usr/bin/python# -*- coding: UTF-8 -*-import time
localtime = time.asctime( time.localtime(time.time()) )print "本地时间为 :", localtime

以上实例输出结果:


本地时间为 : Thu Apr 7 10:05:21 2016

 

格式化日期

我们可以使用 time 模块的 strftime 方法来格式化日期,:


time.strftime(format[, t])
#!/usr/bin/python# -*- coding: UTF-8 -*-import time# 格式化成2016-03-20 11:45:39形式print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 格式化成Sat Mar 28 22:24:24 2016形式print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) 
  # 将格式字符串转换为时间戳a = "Sat Mar 28 22:24:24 2016"print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

以上实例输出结果:


2016-04-07 10:25:09Thu Apr 07 10:25:09 20161459175064.0

 

获取某月日历

Calendar 模块有很广泛的方法用来处理年历和月历,例如打印某月的月历:


#!/usr/bin/python# -*- coding: UTF-8 -*-import calendar
cal = calendar.month(2016, 1)print "以下输出2016年1月份的日历:"print cal;

以上实例输出结果:


以下输出2016年1月份的日历:
    January 2016Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 1011 12 13 14 15 16 1718 19 20 21 22 23 2425 26 27 28 29 30 31

 

更多 Python 课程:https://edu.aliyun.com/course/137/lesson/list?utm_content=g_1000056646


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69926013/viewspace-2649065/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/69926013/viewspace-2649065/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值