Python中基本的日期时间处理的学习教程

yipeiwu_com6年前Python基础

Python程序能用很多方式处理日期和时间。转换日期格式是一个常见的例行琐事。Python有一个 time 和 calendar 模组可以帮忙。
什么是Tick?
时间间隔是以秒为单位的浮点小数。
每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。
Python附带的受欢迎的time模块下有很多函数可以转换常见日期格式。如函数time.time()用ticks计时单位返回从12:00am, January 1, 1970(epoch) 开始的记录的当前操作系统时间, 如下实例:

#!/usr/bin/python
import time; # This is required to include time module.

ticks = time.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks

以上实例输出结果:

Number of ticks since 12:00am, January 1, 1970: 7186862.73399


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

什么是时间元组?
很多Python函数用一个元组装起来的9组数字处理时间:

上述也就是struct_time元组。这种结构具有如下属性:

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

#!/usr/bin/python
import time;

localtime = time.localtime(time.time())
print "Local current time :", localtime

以上实例输出结果:

Local current time : time.struct_time(tm_year=2013, tm_mon=7, 
tm_mday=17, tm_hour=21, tm_min=26, tm_sec=3, tm_wday=2, tm_yday=198, tm_isdst=0)


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

#!/usr/bin/python
import time;

localtime = time.asctime( time.localtime(time.time()) )
print "Local current time :", localtime

以上实例输出结果:

Local current time : Tue Jan 13 10:17:09 2009


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

#!/usr/bin/python
import calendar

cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal;

以上实例输出结果:

Here is the calendar:
  January 2008
Mo Tu We Th Fr Sa Su
  1 2 3 4 5 6
 7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

相关文章

python SVD压缩图像的实现代码

python SVD压缩图像的实现代码

前言 利用SVD是可以对图像进行压缩的,其核心原因在于,图像的像素之间具有高度的相关性。 代码 # -*- coding: utf-8 -*- ''' author@cclplu...

了解不常见但是实用的Python技巧

了解不常见但是实用的Python技巧

1.交换变量值 2.将一列表中的所有元素拼接成字符串 3.查找list中最高频率的值 4.检查两个单词是否是字谜(组成的字母和对应数量一致) 5.反转字符串 6.反转列表 7...

python ddt数据驱动最简实例代码

在接口自动化测试中,往往一个接口的用例需要考虑 正确的、错误的、异常的、边界值等诸多情况,然后你需要写很多个同样代码,参数不同的用例。如果测试接口很多,不但需要写大量的代码,测试数据和代...

Tornado实现多进程/多线程的HTTP服务详解

用tornado web服务的基本流程 1.实现处理请求的Handler,该类继承自tornado.web.RequestHandler,实现用于处理请求的对应方法如:get、post...

Tensorflow实现卷积神经网络的详细代码

本文实例为大家分享了Tensorflow实现卷积神经网络的具体代码,供大家参考,具体内容如下 1.概述 定义: 卷积神经网络(Convolutional Neural Network,...