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. 转:HTTPS 升级指南

    上一篇文章我介绍了 HTTP/2 协议 ,它只有在 HTTPS 环境才会生效. 为了升级到 HTTP/2 协议,必须先启用 HTTPS.如果你不了解 HTTPS 协议(学名 TLS 协议),可以参考我 ...

  2. UVa 793 - Network Connections

    题目大意:给出计算机之间的连接配置,询问某两台计算机是否相连.判断两个点是否在同一个连通分量里,用并查集处理. #include <cstdio> #define MAXN 1000000 ...

  3. Java IO面试

    1. 讲讲IO里面的常见类,字节流.字符流.接口.实现类.方法阻塞. 字节流和字符流的区别: 1)字节流处理单元为1个字节,操作字节和字节数组,而字符流处理的单元为2个字节的Unicode字符,分别操 ...

  4. bzoj 1036

    1036: [ZJOI2008]树的统计Count Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 11858  Solved: 4803[Submit ...

  5. JDBC连接sql server数据库的详细步骤和代码

    JDBC连接sql server数据库的详细步骤和代码 JDBC连接sql server数据库的步骤如下: 1.加载JDBC驱动程序: 在连接数据库之前,首先要加载想要连接的数据库的驱动到JVM(Ja ...

  6. MVC 与 MVVM

    MVC View直接访问Model,View包含Model信息,包括业务逻辑. MVC模型里Model不变,Model不依赖于View,但是 View依赖于Model.因为View实现了一些业务逻辑, ...

  7. iOS 之 数组指针

    int a[5]={1,2,3,4,5}; int *p=(int*)(&a+1); //p 相当于int (*p) [5] = &a; // &a+1 p相当于,p移动了a本 ...

  8. localToLocal坐标变换

    localToLocal坐标变换 $(function() { init(); }); // localtoLocal var stage, arm, handler; function init(e ...

  9. 大数据时代的杀手锏----Tachyon

    一.Tachyon系统的简介 Tachyon是一个分布式内存文件系统,可以在集群里以访问内存的速度来访问存在tachyon里的文件.把 Tachyon是架构在最底层的分布式文件存储和上层的各种计算框架 ...

  10. Java线程:线程交互

    一.基础知识 java.lang.Object的类的三个方法: void notify():唤醒在此对象监视器上等待的单个线程. void notifyAll():唤醒在此对象监视器上等待的所有线程. ...