Python的标准模块datetime模块,在我们的工作中应用非常频繁,下面对datetime中常用的方法进行了总结和测试;对每一个方法都使用了单元测试框架Unittest来配合测试。

主要的类型有:

  首先要导入datetime模块:from datetime import datetime, timedelta, timezone

  一、自己定义时间格式:1、datetime(2017,2,22,16,5,26);2、datetime.strptime('2017-02-22 16:05:26', '%Y-%m-%d %H:%M:%S')

  二、将datetime转化成timestamp格式:datetime(2017,2,22,16,5,26).timestamp()

  三、将timestamp转化成datetime格式:datetime.fromtimestamp(1487750726.0)

  四、将datetime转化成str格式:datetime(2017,2,22,16,5,26).strftime('%Y-%m-%d %H:%M:%S')

  五、利用timedelta进行时间相加:datetime.strptime('2017-02-22 16:05:26', '%Y-%m-%d %H:%M:%S') + timedelta(hours=10, days=2)

  六、利用timedelta进行时间相减:datetime.strptime('2017-02-22 14:05:26', '%Y-%m-%d %H:%M:%S') - timedelta(hours=1)

  八、转换时区:

  utc_datetime = datetime.strptime('2017-02-22 17:05:26', '%Y-%m-%d %H:%M:%S').replace(tzinfo=timezone(timedelta(hours=8)))
  # 北京时间
  bj_datetime = utc_datetime.astimezone(timezone(timedelta(hours=8)))
  # 东京时间
  dj_datetime = bj_datetime.astimezone(timezone(timedelta(hours=9)))

  下面的就是代码,testDatetime.py:

# coding=utf-8

"""
testDatetime.py
datetime模块练习
"""
import unittest
from datetime import datetime, timedelta, timezone class TestDatetime(unittest.TestCase): def test_get_datetime(self):
"""指定日期和时间datetime"""
expected = "2017-02-22 16:05:26"
actual = datetime(2017,2,22,16,5,26)
# print(actual)
self.assertEqual(expected, str(actual)) def test_datetime_translation_timestamp(self):
"""将datetime转化成timestamp,返回的是秒"""
expected = 1487750726.0
actual = datetime(2017,2,22,16,5,26).timestamp()
# print(type(actual))
self.assertEqual(expected, actual) def test_timestamp_translation_datetime(self):
"""将timestamp转化成datetime格式"""
expected = "2017-02-22 16:05:26"
actual = datetime.fromtimestamp(1487750726.0)
# print(actual)
self.assertEqual(expected, str(actual)) def test_str_translation_datetime(self):
"""将str转化成datetime格式"""
expected = datetime(2017,2,22,16,5,26)
actual = datetime.strptime('2017-02-22 16:05:26', '%Y-%m-%d %H:%M:%S')
# print(actual)
self.assertEqual(expected, actual) def test_datetime_translation_str(self):
"""将datetime转化成str"""
excepted = '2017-02-22 16:05:26'
actual = datetime(2017,2,22,16,5,26).strftime('%Y-%m-%d %H:%M:%S')
# print(type(actual))
self.assertEqual(excepted, actual) def test_datetime_add(self):
"""利用timedelta进行时间相加"""
# 加1小时
excepted1 = datetime.strptime('2017-02-22 17:05:26', '%Y-%m-%d %H:%M:%S')
actual1 = datetime.strptime('2017-02-22 16:05:26', '%Y-%m-%d %H:%M:%S') + timedelta(hours=1)
# 加2天,10小时
excepted2 = datetime.strptime('2017-02-25 02:05:26', '%Y-%m-%d %H:%M:%S')
actual2 = datetime.strptime('2017-02-22 16:05:26', '%Y-%m-%d %H:%M:%S') + timedelta(hours=10, days=2) self.assertEqual(excepted1, actual1)
self.assertEqual(excepted2, actual2) def test_datetime_plus(self):
"""利用timedelta进行时间相减"""
# 减1小时
excepted1 = datetime.strptime('2017-02-22 16:05:26', '%Y-%m-%d %H:%M:%S')
actual1 = datetime.strptime('2017-02-22 17:05:26', '%Y-%m-%d %H:%M:%S') - timedelta(hours=1)
self.assertEqual(excepted1, actual1) def test_timezone_translation(self):
"""转换时区"""
utc_datetime = datetime.strptime('2017-02-22 17:05:26', '%Y-%m-%d %H:%M:%S').replace(tzinfo=timezone(timedelta(hours=8)))
# 北京时间
bj_datetime = utc_datetime.astimezone(timezone(timedelta(hours=8)))
# 东京时间
dj_datetime = bj_datetime.astimezone(timezone(timedelta(hours=9)))
# print(dj_datetime)
self.assertEqual((bj_datetime + timedelta(hours=1)).strftime('%Y-%m-%d %H:%M:%S'), dj_datetime.strftime('%Y-%m-%d %H:%M:%S')) if __name__ == '__main__':
unittest.main()

  还有测试结果图(全部测试通过):

Python,datetime模块实例的更多相关文章

  1. python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客

    python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客     python datetime模块strptime/strptime form ...

  2. python datetime模块参数详解

    Python提供了多个内置模块用于操作日期时间,像calendar,time,datetime.time模块,它提供 的接口与C标准库time.h基本一致.相比于time模块,datetime模块的接 ...

  3. Python datetime模块的介绍

    datetime模块常用的主要有下面这四个类:(要清楚import datetime : 导入的是datetime这个包,包里有各种类) 1. datetime.date   用于表示年月日构成的日期 ...

  4. python——datetime模块

    一.datetime模块介绍 (一).datetime模块中包含如下类: 类名 功能说明 date 日期对象,常用的属性有year, month, day time 时间对象 datetime 日期时 ...

  5. Python datetime模块的datetime类

    datetime模块定义了下面这几个类: datetime.date:表示日期的类.常用的属性有year, month, day. datetime.time:表示时间的类.常用的属性有hour, m ...

  6. Python 日志模块实例

    python 打印对象的所有属性值: def prn_obj(obj):     print '\n'.join(['%s:%s' % item for item in obj.__dict__.it ...

  7. python datetime模块详解

    datetime是python当中比较常用的时间模块,用于获取时间,时间类型之间转化等,下文介绍两个实用类. 一.datetime.datetime类: datetime.datetime.now() ...

  8. Python: json模块实例详解

    ref:https://www.jianshu.com/p/e29611244810 https://www.cnblogs.com/qq78292959/p/3467937.html https:/ ...

  9. python datetime模块

    该模块的时间有限时限:1 - 9999 dir(datetime)  from datetime import datetime, timedelta, timezone dt = datetime. ...

随机推荐

  1. cocoaPods的安装使用 以及 Carthage

    http://cnbin.github.io/blog/2015/05/25/cocoapods-an-zhuang-he-shi-yong/ 按照这个步骤就OK Note:当引入已有的project ...

  2. Python collections.defaultdict() 与 dict的使用和区别

    看样子这个文档是难以看懂了.直接看示例: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import collections s = [('yellow', ...

  3. BZOJ1237: [SCOI2008]配对

    传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1237 题目大意:你有n 个整数Ai和n 个整数Bi.你需要把它们配对,即每个Ai恰好对应一 ...

  4. php实现MD5加密16位(不要默认的32位)

    使用substr函数截取: substr(md5("admin"),8,16); // 16位MD5加密 md5("admin"); // 32位MD5加密

  5. php-fpm 相关

    ps aux | grep -c php-fpm 查看php-fpm进程数:ps aux | grep -c php-fpm 查看运行内存/usr/bin/php  -i|grep mem 重启php ...

  6. Nginx中的信号量(信号控制)

  7. python 自动化之路 day 13

    本节内容参考博客: http://www.cnblogs.com/wupeiqi/articles/5132791.html http://www.cnblogs.com/wupeiqi/articl ...

  8. .net 设置版本号信息

    1.AssemblyInfo.cs [assembly: AssemblyVersion("1.3.170116")] [assembly: AssemblyFileVersion ...

  9. js模块化开发——require.js学习总结

    1.为什么使用require.js 作为命名空间: 作为命名空间使用: 异步加载js,避免阻塞,提高性能: js通过require加载,不必写很多script 2.require.js的加载 requ ...

  10. redhat6.4下安装Oracle11g

    一.在Root用户下执行以下步骤: 1)修改用户的SHELL的限制,修改/etc/security/limits.conf文件 *               soft    nproc  2047 ...