`
mcjiffy
  • 浏览: 18271 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
最近访客 更多访客>>
社区版块
存档分类
最新评论

python的time和date处理

阅读更多
内置模块time包含很多与时间相关函数。我们可通过它获得当前的时间和格式化时间输出。
time(),以浮点形式返回自Linux新世纪以来经过的秒数。在linux中,00:00:00 UTC, January 1, 1970是新**49**的开始。
strftime可以用来获得当前时间,可以将时间格式化为字符串等等,还挺方便的。但是需要注意的是获得的时间是服务器的时间,注意时区问题,比如gae撒谎那个的时间就是格林尼治时间的0时区,需要自己转换。

strftime()函数将时间格式化
我们可以使用strftime()函数将时间格式化为我们想要的格式。它的原型如下:

size_t strftime(
char *strDest,
size_t maxsize,
const char *format,
const struct tm *timeptr
);

我们可以根据format指向字符串中格式命令把timeptr中保存的时间信息放在strDest指向的字符串中,最多向strDest中存放maxsize个字符。该函数返回向strDest指向的字符串中放置的字符数。

strftime使时间格式化。python的strftime格式是C库支持的时间格式的真子集。

  %a 星期几的简写 Weekday name, abbr.
  %A 星期几的全称 Weekday name, full
  %b 月分的简写 Month name, abbr.
  %B 月份的全称 Month name, full
  %c 标准的日期的时间串 Complete date and time representation
  %d 十进制表示的每月的第几天 Day of the month
  %H 24小时制的小时 Hour (24-hour clock)
  %I 12小时制的小时 Hour (12-hour clock)
  %j 十进制表示的每年的第几天 Day of the year
  %m 十进制表示的月份 Month number
  %M 十时制表示的分钟数 Minute number
  %S 十进制的秒数 Second number
  %U 第年的第几周,把星期日做为第一天(值从0到53)Week number (Sunday first weekday)
  %w 十进制表示的星期几(值从0到6,星期天为0)weekday number
  %W 每年的第几周,把星期一做为第一天(值从0到53) Week number (Monday first weekday)
  %x 标准的日期串 Complete date representation (e.g. 13/01/08)
  %X 标准的时间串 Complete time representation (e.g. 17:02:10)
  %y 不带世纪的十进制年份(值从0到99)Year number within century
  %Y 带世纪部分的十制年份 Year number
  %z,%Z 时区名称,如果不能得到时区名称则返回空字符。Name of time zone
  %% 百分号

1. # handling date/time data
   2. # Python23 tested vegaseat 3/6/2005
   3.
   4. import time
   5.
   6. print "List the functions within module time:"
   7. for funk in dir(time):
   8. print funk
   9.
  10. print time.time(), "seconds since 1/1/1970 00:00:00"
  11. print time.time()/(60*60*24), "days since 1/1/1970"
  12.
  13. # time.clock() gives wallclock seconds, accuracy better than 1 ms
  14. # time.clock() is for windows, time.time() is more portable
  15. print "Using time.clock() = ", time.clock(), "seconds since first call to clock()"
  16. print "\nTiming a 1 million loop 'for loop' ..."
  17. start = time.clock()
  18. for x in range(1000000):
  19. y = x # do something
  20. end = time.clock()
  21. print "Time elapsed = ", end - start, "seconds"
  22.
  23. # create a tuple of local time data
  24. timeHere = time.localtime()
  25. print "\nA tuple of local date/time data using time.localtime():"
  26. print "(year,month,day,hour,min,sec,weekday(Monday=0),yearday,dls-flag)"
  27. print timeHere
  28.
  29. # extract a more readable date/time from the tuple
  30. # eg. Sat Mar 05 22:51:55 2005
  31. print "\nUsing time.asctime(time.localtime()):", time.asctime(time.localtime())
  32. # the same results
  33. print "\nUsing time.ctime(time.time()):", time.ctime(time.time())
  34. print "\nOr using time.ctime():", time.ctime()
  35.
  36. print "\nUsing strftime():"
  37. print "Day and Date:", time.strftime("%a %m/%d/%y", time.localtime())
  38. print "Day, Date :", time.strftime("%A, %B %d, %Y", time.localtime())
  39. print "Time (12hr) :", time.strftime("%I:%M:%S %p", time.localtime())
  40. print "Time (24hr) :", time.strftime("%H:%M:%S", time.localtime())
  41. print "DayMonthYear:",time.strftime("%d%b%Y", time.localtime())
  42.
  43. print
  44.
  45. print "Start a line with this date-time stamp and it will sort:",\
  46. time.strftime("%Y/%m/%d %H:%M:%S", time.localtime())
  47.
  48. print
  49.
  50. def getDayOfWeek(dateString):
  51. # day of week (Monday = 0) of a given month/day/year
  52. t1 = time.strptime(dateString,"%m/%d/%Y")
  53. # year in time_struct t1 can not go below 1970 (start of epoch)!
  54. t2 = time.mktime(t1)
  55. return(time.localtime(t2)[6])
  56.
  57. Weekday = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
  58. 'Friday', 'Saturday', 'Sunday']
  59.
  60. # sorry about the limitations, stay above 01/01/1970
  61. # more exactly 01/01/1970 at 0 UT (midnight Greenwich, England)
  62. print "11/12/1970 was a", Weekday[getDayOfWeek("11/12/1970")]
  63.
  64. print
  65.
  66. print "Calculate difference between two times (12 hour format) of a day:"
  67. time1 = raw_input("Enter first time (format 11:25:00AM or 03:15:30PM): ")
  68. # pick some plausible date
  69. timeString1 = "03/06/05 " + time1
  70. # create a time tuple from this time string format eg. 03/06/05 11:22:00AM
  71. timeTuple1 = time.strptime(timeString1, "%m/%d/%y %I:%M:%S%p")
  72.
  73. #print timeTuple1 # test eg. (2005, 3, 6, 11, 22, 0, 5, 91, -1)
  74.
  75. time2 = raw_input("Enter second time (format 11:25:00AM or 03:15:30PM): ")
  76. # use same date to stay in same day
  77. timeString2 = "03/06/05 " + time2
  78. timeTuple2 = time.strptime(timeString2, "%m/%d/%y %I:%M:%S%p")
  79.
  80. # mktime() gives seconds since epoch 1/1/1970 00:00:00
  81. time_difference = time.mktime(timeTuple2) - time.mktime(timeTuple1)
  82. #print type(time_difference) # test <type 'float'>
  83. print "Time difference = %d seconds" % int(time_difference)
  84. print "Time difference = %0.1f minutes" % (time_difference/60.0)
  85. print "Time difference = %0.2f hours" % (time_difference/(60.0*60))
  86.
  87. print
  88.
  89. print "Wait one and a half seconds!"
  90. time.sleep(1.5)
  91. print "The end!"

原文地址:http://blog.chinaunix.net/u/11263/showart_1836187.html
分享到:
评论

相关推荐

    测量程序编制 - python 59格式化输出:datetime模块(date类).pptx

    Python中提供了多个用于对日期和时间进行操作的内置模块:time模块、datetime模块和calendar模块。其中time模块是通过调用C库实现的,所以有些方法在某些平台上可能无法调用,但是其提供的大部分接口与C标准库time.h...

    Python之日期与时间处理模块(date和datetime)

    Python中提供了多个用于对日期和时间进行操作的内置模块:time模块、datetime模块和calendar模块。其中time模块是通过调用C库实现的,所以有些方法在某些平台上可能无法调用,但是其提供的大部分接口与C标准库time.h...

    Python之time模块的时间戳,时间字符串格式化与转换方法(13位时间戳)

    Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。 关于时间戳的几个概念 时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。 时间元组(struct_time),包含9个元素。 time....

    python的time模块和datetime模块实例解析

    主要介绍了python的time模块和datetime模块实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    TimeDate.py

    关于python3时间与日期中的一些常用的功能展示,代码,使用pycharm编写

    Python中time模块与datetime模块在使用中的不同之处

    Python 中提供了对时间日期的多种多样的处理方式,主要是在 time 和 datetime 这两个模块里。今天稍微梳理一下这两个模块在使用上的一些区别和联系。 time 在 Python 文档里,time是归类在Generic Operating System ...

    详解python时间模块中的datetime模块

    Python提供了多个内置模块用于操作...函数datetime.combine(date,time)可以得到dateime,datetime.date()、datetime.time()可以获得date和time 2、datetime time 与string的转换 今天就来讲讲datetime模块。 1、datet

    支持原生接口的 ClickHouse Python驱动程序_Python_代码_相关文件_下载

    Date/Date32/DateTime('timezone')/DateTime64('timezone') 字符串/固定字符串(N) 枚举8/16 数组(T) 可空(T) 布尔 UUID 十进制 IPv4/IPv6 低基数(T) SimpleAggregateFunction(F, T) 元组(T1,T2,...) 嵌套 映射...

    Python: The Ultimate Python Quickstart Guide - From Beginner To Expert [2016]

    Learning one of the most prominent and dynamic programming language to date, which has evolved itself to be as much powerful and versatile as Java or C++, but is much friendlier to new programmers!...

    python时间日期函数与利用pandas进行时间序列处理详解

    python标准库包含于日期(date)和时间(time)数据的数据类型,datetime、time以及calendar模块会被经常用到。 datetime以毫秒形式存储日期和时间,datetime.timedelta表示两个datetime对象之间的时间差。 下面我们...

    python中关于时间和日期函数的常用计算总结(time和datatime)

    1.获取当前时间的两种方法: ...复制代码 代码如下:last = datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)print last 3.获取时间差(时间差单位为秒,常用于

    Modern Python Standard Library Cookbook

    You will learn to work with multimedia components and perform mathematical operations on date and time. The recipes will also show you how to deploy different searching and sorting algorithms on your...

    Beginning Python(Apress,3ed,2017)

    Gain a fundamental understanding of Python’s syntax and features with this up–to–date introduction and practical reference. Covering a wide array of Python–related programming topics, including ...

    python3.6.5参考手册 chm

    Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python What’s New In ...

    Python for Finance Analyze Big Financial Data

    Fundamentals: Python data structures, NumPy array handling, time series analysis with pandas, visualization with matplotlib, high performance I/O operations with PyTables, date/time information ...

    Python3.5内置模块之time与datetime模块用法实例分析

    本文实例讲述了Python3.5内置模块之time与datetime模块用法。分享给大家供大家参考,具体如下: 1、模块的分类 a、标准库(Python自带):sys、os模块 b、开源模块(第三方模块) c、自定义模块 2、内建模块——...

    MySQL for Python - 完美列印版.pdf

    Chapter 9: Date and Time Values 247 Chapter 10: Aggregate Functions and Clauses 279 Chapter 11: SELECT Alternatives 311 Chapter 12: String Functions 341 Chapter 13: Showing MySQL Metadata 369 Chapter ...

    HTMLTestRunner中文版Python3.X

    path= 'D:/Python_test/'+ date +"/login/"+time+"/" #定义报告文件路径和名字,路径为前面定义的path,名字为report(可自定义),格式为.html report_path = path+"report.html" #判断是否定义的路径目录...

    第一个python项目,用于学习和练习.rar

    你可以使用date-time模块创建闹钟,以及playsound库播放声音。 from datetime import datetime from playsound import playsound alarm_time = input("Enter the time of alarm to be set:HH:MM:SS\n") alarm_hour...

Global site tag (gtag.js) - Google Analytics