zoukankan      html  css  js  c++  java
  • 【Python爬虫实战--2】时间戳转换为指定格式日期

    摘自:http://www.2cto.com/kf/201406/311477.html

    (1)方法:

    方法一:
            利用localtime()转换为时间数组,然后格式化为需要的格式,如
            timeStamp = 1381419600
            timeArray = time.localtime(timeStamp)
            otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
            otherStyletime == "2013-10-10 23:40:00"
      
    方法二:
            import datetime
            timeStamp = 1381419600
            dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
            otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
            otherStyletime == "2013-10-10 23:40:00"

    (2)我遇到的问题是:

    ...
    print
    u"第%d页 发布人:%s 发布时间:%s 赞:%s %s" %(page,story[0],story[2], story[3], story[1])

    运行结果:

    第1页    发布人:心在远方?    发布时间:1445500414    赞:11741
    老妈有点多愁善感,一天问我,你以后会不会找了媳妇就忘了你妈我啊,我很严肃的跟妈妈说,妈你说什么呢,我是那种能娶到媳妇的人吗?
    ...

    但是,我希望运行出来的发布时间改为指定格式,所以我改了代码,如下:

    ...
    print u"第%d页	发布人:%s	发布时间:%s	赞:%s
    %s" %(page,story[0], time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(story[2]))), story[3], story[1])
    from datetime import datetime
    print u"第%d页	发布人:%s	发布时间:%s	赞:%s
    %s" %(page,story[0], datetime.fromtimestamp(int(story [2])), story[3], story [1]))
    print u"第%d页	发布人:%s	发布时间:%s	赞:%s
    %s" %(page, story[0], (datetime.utcfromtimestamp(float(story[2]))).strftime("%Y-%m-%d %H:%M:%S"), story[3], story[1])

    运行结果:

    第1页    发布人:心在远方?    发布时间:2015-10-22 15:53:34    赞:11749
    老妈有点多愁善感,一天问我,你以后会不会找了媳妇就忘了你妈我啊,我很严肃的跟妈妈说,妈你说什么呢,我是那种能娶到媳妇的人吗?
  • 相关阅读:
    PHP数组(数组正则表达式、数组、预定义数组)
    面向对象。OOP三大特征:封装,继承,多态。 这个讲的是【封存】
    uvalive 3938 "Ray, Pass me the dishes!" 线段树 区间合并
    LA4329 Ping pong 树状数组
    HDU 1257 最少拦截系统
    HDU 1260 Tickets
    codeforce 621D
    codeforce 621C Wet Shark and Flowers
    codeforce 621B Wet Shark and Bishops
    codeforce 621A Wet Shark and Odd and Even
  • 原文地址:https://www.cnblogs.com/chamie/p/4904544.html
Copyright © 2011-2022 走看看