Python,datetime模块实例
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模块实例的更多相关文章
- python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客
python datetime模块strptime/strptime format常见格式命令_施罗德_新浪博客 python datetime模块strptime/strptime form ...
- python datetime模块参数详解
Python提供了多个内置模块用于操作日期时间,像calendar,time,datetime.time模块,它提供 的接口与C标准库time.h基本一致.相比于time模块,datetime模块的接 ...
- Python datetime模块的介绍
datetime模块常用的主要有下面这四个类:(要清楚import datetime : 导入的是datetime这个包,包里有各种类) 1. datetime.date 用于表示年月日构成的日期 ...
- python——datetime模块
一.datetime模块介绍 (一).datetime模块中包含如下类: 类名 功能说明 date 日期对象,常用的属性有year, month, day time 时间对象 datetime 日期时 ...
- Python datetime模块的datetime类
datetime模块定义了下面这几个类: datetime.date:表示日期的类.常用的属性有year, month, day. datetime.time:表示时间的类.常用的属性有hour, m ...
- Python 日志模块实例
python 打印对象的所有属性值: def prn_obj(obj): print '\n'.join(['%s:%s' % item for item in obj.__dict__.it ...
- python datetime模块详解
datetime是python当中比较常用的时间模块,用于获取时间,时间类型之间转化等,下文介绍两个实用类. 一.datetime.datetime类: datetime.datetime.now() ...
- Python: json模块实例详解
ref:https://www.jianshu.com/p/e29611244810 https://www.cnblogs.com/qq78292959/p/3467937.html https:/ ...
- python datetime模块
该模块的时间有限时限:1 - 9999 dir(datetime) from datetime import datetime, timedelta, timezone dt = datetime. ...
随机推荐
- Unity3D ——强大的跨平台3D游戏开发工具(二)
第二章 Unity3D的简单预览 每个Unity3D版本都会自带一个Demo源文件.在3.0的正式版中,自带的Demo就是网上展示的那款强大的射击游戏.在一般情况下,您只要第一次 打开Unity3D ...
- JavaScript高级程序设计-10.11: DOM及其扩展
什么是DOM? DOM(文档对象模型)是针对 HTML 和 XML 文档的一个 API(应用程序编程接口).DOM描绘了一个层次化的节点树,允许开发人员添加.移除和修改页面的某一部分. 文档节点(do ...
- IO文件
在Windows下的路径分隔符和Linux下的路径分隔符是不一样的,当直接使用绝对路径时,跨平台会暴出“No such file or diretory”的异常. Separator: 比如说要在te ...
- 大数据竞赛平台——Kaggle 入门
Reference: http://blog.csdn.net/witnessai1/article/details/52612012 Kaggle是一个数据分析的竞赛平台,网址:https://ww ...
- Eclipse配置Git发布项目到Github
很牛叉的博客http://blog.csdn.net/luckarecs/article/details/7427605 一.安装插件 菜单栏Help --> Install New Softw ...
- IOS 利用图片设置背景
UIImageView* imageView = [[UIImageView alloc] initWithFrame:self.view.bounds]; imageView.image = [UI ...
- 基于jquery 封装的 select 小控件,解决 IE6 7 8里 select 边框 高度 无法遮挡等问题
一.基本原理 select控件在浏览器中是个永远的痛,不同的版本解析出来的可谓五花八门.主要有以下问题: 1,IE6中无法设置高度,Z INDEX永远在最上,无法被其它层遮挡 2,IE7中可以设置高度 ...
- 5分钟了解MySQL5.7的Online DDL雷区
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://suifu.blog.51cto.com/9167728/1855872 Part ...
- 2.1. 托管对象模型是什么(Core Data 应用程序实践指南)
托管对象模型是一种数据结构.在这里,数据结构.纲要.对象图.数据模型.托管对象模型这些术语是一个意思.它们是对同一个东西不同场景的描述.比如,对Core Data 而言是托管对象模型,对设计器来说是对 ...
- js架构设计模式——前端MVVM框架设计及实现(二)
前端MVVM框架设计及实现(二) 在前端MVVM框架设计及实现(一)中有一个博友提出一个看法: “html中使用mvvm徒增开发成本” 我想这位朋友要表达的意思应该是HTML定义了大量的语法标记,HT ...