免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4490 | 回复: 0
打印 上一主题 下一主题

python中的时间 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-09-28 22:09 |只看该作者 |倒序浏览
来源:
http://wjason.javaeye.com/blog/406874

关键字: python, time, struts_time, datetime
最近写了两个python脚本, 他们都用到了python中的时间.

第一个脚本的背景是: 在一个维护的项目里面,每次Release都要更新一批文件, 有一个Excel文件专门管理这些变更文件的时间戳, 在Excel中客户要求填写变更的文件以及他们对应的最后编辑时间.

于是第一个脚本解决解决的需求便是: 批量获取一堆制定文件的时间戳.
维护的项目都差不多, 以前用java写过一个根据时间戳, 判断变更文件列表的东西, 代码确实没有python简洁,
不罗嗦了,这个脚本的代码如下:
Python代码

  • __author__="wjason"  
  • __date__ ="$2009-6-1 11:04:09$"  
  •   
  • filesList = [   
  •         "xmldata/DataDict_en_GB.xml",   
  •         "xmldata/DataDict_en_US.xml",   
  •         "ReleaseNotes/ReleaseNotes_en.txt",   
  •         "ReleaseNotes/ReleaseNotes_ja.txt",   
  •         "Code/AAA.java",   
  •         "Code/daemon/BBB.java"  
  • ]   
  •   
  • if __name__ == "__main__":   
  •     import os,time   
  •       
  •     filePath = "K:/release/history/2.24.1/Other/"  
  •     # this result is csv format. seperated by ","   
  •     result = [ fn +","+ time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(os.stat(filePath+fn).st_mtime))   
  •                for fn in filesList]   
  •     print '\n'.join(result)  __author__="wjason"
    __date__ ="$2009-6-1 11:04:09$"
    filesList = [
            "xmldata/DataDict_en_GB.xml",
            "xmldata/DataDict_en_US.xml",
            "ReleaseNotes/ReleaseNotes_en.txt",
            "ReleaseNotes/ReleaseNotes_ja.txt",
            "Code/AAA.java",
            "Code/daemon/BBB.java"
    ]
    if __name__ == "__main__":
        import os,time
       
        filePath = "K:/release/history/2.24.1/Other/"
        # this result is csv format. seperated by ","
        result = [ fn +","+ time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(os.stat(filePath+fn).st_mtime))
                   for fn in filesList]
        print '\n'.join(result)


    第二个脚本的背景是: 项目的日报以周为单位, 我们有一个日报模板, 我的工作是每周一将我们的日报模板拷贝一份,
    并重命名为本周的日报. 命名规则是:"这周周一的日期~这周周五的日期" + "日报"的形式.
    于是这个脚本的任务是以适当的名字拷贝日报模板. 无论他在任何时间被运行, 如果本周的日报不存在, 他都将创建出来.
    脚本被放在计划任务里面执行,代码如下:

    Python代码

  • #! /usr/bin/python   
  • #coding:utf-8   
  •   
  • __author__="wjason"  
  • __date__ ="$2009-6-10 11:32:31$"  
  •   
  • import os,time,datetime   
  •   
  • def generateFileName():   
  •     ct = datetime.datetime.now()   
  •     week  = ct.weekday()   
  •   
  •     startDay = ct + datetime.timedelta(days= (0 - week))   
  •     endDay   = ct + datetime.timedelta(days= (4 - week))   
  •   
  •     startStr =  startDay.strftime("%y%m%d")   
  •     endStr =  endDay.strftime("%y%m%d")   
  •       
  •     filename = startStr + "~" + endStr + "日報.xls"  
  •     return filename   
  •   
  • if __name__ == "__main__":   
  •     path = "\\\\fileserver\\作業報告path"  
  •     source = path +"\\日報のTemplate.xls"  
  •     dest = path + "\\" + generateFileName()   
  •     if(os.path.exists(dest)):   
  •         print "ERROR:  dest is existed."  
  •     else:   
  •         cmd = "cp -u " +"  "+source+"  "+dest   
  •         print cmd   
  •         os.popen(cmd)   
  •         print "Finished."  #! /usr/bin/python
    #coding:utf-8
    __author__="wjason"
    __date__ ="$2009-6-10 11:32:31$"
    import os,time,datetime
    def generateFileName():
        ct = datetime.datetime.now()
        week  = ct.weekday()
        startDay = ct + datetime.timedelta(days= (0 - week))
        endDay   = ct + datetime.timedelta(days= (4 - week))
        startStr =  startDay.strftime("%y%m%d")
        endStr =  endDay.strftime("%y%m%d")
       
        filename = startStr + "~" + endStr + "日報.xls"
        return filename
    if __name__ == "__main__":
        path = "\\\\fileserver\\作業報告path"
        source = path +"\\日報のTemplate.xls"
        dest = path + "\\" + generateFileName()
        if(os.path.exists(dest)):
            print "ERROR:  dest is existed."
        else:
            cmd = "cp -u " +"  "+source+"  "+dest
            print cmd
            os.popen(cmd)
            print "Finished."  

    总结:
    在这两个脚本里面都使用到了时间, 搞得我很迷糊, 于是总结整理如下:
    1. python中跟时间有管理的module有两个: time,datetime。
        其中包含了创建时间,转换时间,对时间进行运算的函数。
    2. python中有三种表示, 分别是:
    写道
    a.   一个float
    b.   time module中的struct_time
    c.   datetime module中的datetime class
       他们三个之间可以相互转换.

    3. time,datetime这两个module都有一个叫ctime()的函数,他们都返回一个字符串。
        当然对字符串进行格式化操作还可以用:strftime()

    4. time,datetime这两个module都有一个叫strptime()的函数, 他们执行的是3中的反操作:将字符串变成时间,
        注: time中的得到的是struts_time, datetime中的得到的是datetime object.

    5. datetime中的datetime配合datetime.timedelta可以对时间进行运算。

    至于关于其他的函数在什么时候都返回那种时间表示?上述的三种时间表示如何转化?
    可以参考下面的测试代码,其中每个测试代表一个问题:

    Python代码

  • #! /usr/bin/python   
  •   
  • __author__="wjason"  
  • __date__ ="$2009-6-11 13:52:20$"  
  •   
  • if __name__ == "__main__":   
  •     import time,datetime   
  •   
  •     print "\n--- ===  #test01: ctime() return a String  === ---"  
  •     t_ctime = time.ctime()   
  •     print t_ctime   
  •     print type(t_ctime)   
  •   
  •     print "\n--- ===  #test02: localtime() return time.struct_time  === ---"  
  •     t_local = time.localtime()   
  •     print type(t_local)   
  •   
  •     print "\n--- ===  #test03:  gmtime() return time.struct_time   === ---"  
  •     t_gm = time.gmtime()   
  •     print type(t_gm)   
  •   
  •     print "\n--- ===  #test04: datetime.now() return 'datetime' object  === ---"  
  •     t_datetime = datetime.datetime.now()   
  •     print type(t_datetime)   
  •   
  •     print "\n--- ===  #test05: convert time.struct_time to 'datatime' object=== ---"  
  •     print t_local   
  •     t_datetime = datetime.datetime(*t_local[:6])   
  •     print t_local[:6]   
  •     print t_datetime   
  •   
  •     print "\n--- ===  #test06: convert 'datatime' object to time.struct_time  === ---"  
  •     t_temp =  t_datetime.timetuple()   
  •     print t_temp   
  •     print type(t_temp)   
  •   
  •     print "\n--- ===  #test07: mktime(struct_time ts) return float which represent the time === ---"  
  •     print "--- ===  #test08: convert struts_time to float  === ---"  
  •     t_mk = time.mktime(t_local)   
  •     print type(t_mk)   
  •   
  •     print "\n--- ===  #test08: localtime(float f) return struct_time === ---"  
  •     print "--- ===  #test08: localtime() and mktime() are inverse function of each other  === ---"  
  •     print "--- ===  #test08: convert float to struts_time  === ---"  
  •     t_local = time.localtime(t_mk)   
  •     print type(t_local)  #! /usr/bin/python
    __author__="wjason"
    __date__ ="$2009-6-11 13:52:20$"
    if __name__ == "__main__":
        import time,datetime
        print "\n--- ===  #test01: ctime() return a String  === ---"
        t_ctime = time.ctime()
        print t_ctime
        print type(t_ctime)
        print "\n--- ===  #test02: localtime() return time.struct_time  === ---"
        t_local = time.localtime()
        print type(t_local)
        print "\n--- ===  #test03:  gmtime() return time.struct_time   === ---"
        t_gm = time.gmtime()
        print type(t_gm)
        print "\n--- ===  #test04: datetime.now() return 'datetime' object  === ---"
        t_datetime = datetime.datetime.now()
        print type(t_datetime)
        print "\n--- ===  #test05: convert time.struct_time to 'datatime' object=== ---"
        print t_local
        t_datetime = datetime.datetime(*t_local[:6])
        print t_local[:6]
        print t_datetime
        print "\n--- ===  #test06: convert 'datatime' object to time.struct_time  === ---"
        t_temp =  t_datetime.timetuple()
        print t_temp
        print type(t_temp)
        print "\n--- ===  #test07: mktime(struct_time ts) return float which represent the time === ---"
        print "--- ===  #test08: convert struts_time to float  === ---"
        t_mk = time.mktime(t_local)
        print type(t_mk)
        print "\n--- ===  #test08: localtime(float f) return struct_time === ---"
        print "--- ===  #test08: localtime() and mktime() are inverse function of each other  === ---"
        print "--- ===  #test08: convert float to struts_time  === ---"
        t_local = time.localtime(t_mk)
        print type(t_local)  
    资源:
    这部分资源网上以搜,很多很多。其中我觉得这篇最为不错:
    Date and Time Representation in Python


    里面涉及了: ISO Strings, Unix time, mxDateTime, matplotlib等等概念以及它们的常用操作。
    可谓应有尽有,同时这里连接里面也有自己的一份References,指向详细的文档。


    本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/61757/showart_2062238.html
  • 您需要登录后才可以回帖 登录 | 注册

    本版积分规则 发表回复

      

    北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
    未成年举报专区
    中国互联网协会会员  联系我们:huangweiwei@itpub.net
    感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

    清除 Cookies - ChinaUnix - Archiver - WAP - TOP