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. 开启分布式事物DTC

    1.web服务器开启分布式事物配置后,数据库服务器的host文件要设置  “IP  web服务器主机名” 的映射,否则会 出现 “与基础事务管理器的通信失败” #跨网段使用TransactionSco ...

  2. Java-设计模式-单例模式-饿汉模式、懒汉模式

    //-------------------------------------------------------------饿汉模式--开始----------------------------- ...

  3. java系列-JDBC的封装

    参考:http://blog.csdn.net/liuhenghui5201/article/details/16369773 一. 1.加载驱动-->>封装    --->> ...

  4. 基于RBAC的权限设计模型

    个部件模型组成,这4个部件模型分别是基本模型RBAC0(Core RBAC).角色分级模型RBAC1(Hierarchal RBAC).角色限制模型RBAC2(Constraint RBAC)和统一模 ...

  5. bzoj1113

    传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1113 题解:单调栈 代码: #include<iostream> #includ ...

  6. iOS 之 界面编程解析

    参考:http://www.cocoachina.com/design/20151225/14789.html 0. 内容概述 基础与本质:说明普遍意义上的UI系统的三大模块,让读者从整体上对UI系统 ...

  7. 如何在windows下载和安装Apache

    进入apache服务器官网http://httpd.apache.org/,这里我们以下载稳定版的httpd 2.4.25为例,点击"Files for Microsoft Windows& ...

  8. 使IE6下PNG背景透明的七种方法任你选

    原文地址:http://blog.csdn.net/mosliang/article/details/6760028 相信如何解决png在ie6下透明的问题困扰了很多人.为了追求更好的页面效果,很多人 ...

  9. P2P之UDP穿透NAT的原理与实现

    首先先介绍一些基本概念: NAT(Network Address Translators),网络地址转换:网络地址转换是在IP地址日益缺乏的情况下产生的,它的主要目的就是为了能够地址重用.NAT分为两 ...

  10. spring mvc handler的三种方式

    springmvc.xml 三种方式不能针对一个controller同时使用 <?xml version="1.0" encoding="UTF-8"?& ...