美文网首页
python datetime中的日期-时间运算

python datetime中的日期-时间运算

作者: AibWang | 来源:发表于2020-01-06 20:49 被阅读0次

    python中的常用的时间运算模块包括time,datetime,datetime支持的格式和操作更多,time模块以秒为单位计算更方便。

    1. 生成一个datetime object

    • datetime.datetime(year, month ,day)
    • datetime.datetime.strptime
    import datetime
    
    # 直接通过给年、月、日、时、分、秒、毫秒、时区赋值生成(年、月、日必须给出,其余参数可以不给)
    tt1 = datetime.datetime(2018, 1, 1, 12, 10, 59, 100)
    
    # 通过 datetime.datetime.strptime 从字符串按照指定格式生成
    timestr = '2019-01-14T15:22:18.123Z'
    tt2 = datetime.datetime.strptime(timestr, "%Y-%m-%dT%H:%M:%S.%fZ")
    
    # =====================================
    > 2018-01-01 12:10:59.000100
    > 2019-01-14 15:22:18.123000
    

    注意:如上述例子所示,%S.%f实现了小数表示秒

    2. datetime的格式:

    • %Y 年份 e.g. 1970, 1988, 2001, 2013
    • %y 年份(未带世纪) e.g. 00, 01, …, 99
    • %m 月份 e.g. 01, 02, …, 12
    • %b 月份 e.g. Jan, Feb, …, Dec
    • %d 天 e.g. 01, 02, …, 31
    • %j 天(decimal number)e.g. 001, 002, …, 366
    • %a 星期 e.g. Sun, Mon, …, Sat (en_US)
    • %A 星期 e.g. Sunday, Monday, …, Saturday (en_US)
    • %w 星期 e.g. 0, 1, …, 6
    • %H 小时(24小时制) e.g. 00, 01, …, 23
    • %I 小时(12小时制) e.g. 01, 02, …, 12
    • %p 上/下午标识 e.g. AM, PM
    • %M 分钟 e.g. 00, 01, …,59
    • %S 秒 e.g. 00, 01, …, 59
    • %f 微秒(6位长度) e.g. 000000, 000001, …, 999999
      =====================
    • %W 一年的第几周 e.g. 00, 01, …, 53
    • %% 标识字符%

    3. 日期-时间运算

    通过 datetime objecttimedelta运算

    # days, seconds, microseconds, milliseconds, minutes, hours, weeks
    new_dtime = tt2 + datetime.timedelta(hours=9, seconds=-10)
    print("\nold time:{}".format(tt1))
    print("new time:{}".format(new_dtime))
    
    # =====================================
    > old time:2018-01-01 12:10:59.000100
    > new time:2019-01-15 00:22:08.123000
    

    将datetime object转换为指定format的字符串(format根据以上第2节定义)

    • datetime_obj.strftime(fomat)
    # transform datetime to a string
    new_dtime_str = new_dtime.strftime('%Y-%m-%dT%H:%M:%S.%f')
    [new_hh, new_mm] = new_dtime_str.split('T')[1].split(':')[:2]
    new_ss = new_dtime_str.split('T')[1].split(':')[2][:5]
    print("\nnew datetime string:" + new_dtime_str)
    print("hour:%s   minute:%s   second:%s\n" % (new_hh, new_mm, new_ss))
    
    # =====================================
    > new datetime string: 2019-01-15T00:22:08.123000
    > hour:00   minute:22   second:08.12
    

    为什么要将datetime object转换为字符串呢?其实在很多情况下,我们需要将日期-时间输出为指定格式,转换为字符串更方便操作,仅需进行字符串的拆分,拼接即可实现。

    参考:

    https://docs.python.org/2/library/datetime.html
    https://blog.csdn.net/u013215956/article/details/86478099

    相关文章

      网友评论

          本文标题:python datetime中的日期-时间运算

          本文链接:https://www.haomeiwen.com/subject/blxlactx.html