时间模块和时间工具

一、time模块

三种格式
时间戳时间:浮点数 单位为秒
时间戳起始时间:
1970.1.1 0:0:0 英国伦敦时间
1970.1.1 8:0:0 我国(东8区)
结构化时间:元组(struct_time)
格式化时间:str数据类型的

 

1、常用方法

import timetime.sleep(secs)   推迟指定的时间运行,单位是秒for i in range(3):time.sleep(1)print(i)

 

2、表示时间的三种方式

时间戳(timestamp)、元组(struct_time)、格式化(str_time)的时间字符串1. 时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。
我们运行“type(time.time())”,返回的是float类型。
print(time.time())  # 1536050072.5732844(1970年1月1日00:00:00到此刻运行time.time()的时间) 2. 结构化时间(struct_time) :struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一周中第几天,一年中第几天,夏令时)
struct_time = time.localtime()  # 我国的时间
print(struct_time) 
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=16, tm_min=40, tm_sec=1, tm_wday=1, tm_yday=247, tm_isdst=0)
struct_time = time.gmtime()  # 伦敦的时间
print(struct_time) 
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=8, tm_min=40, tm_sec=1, tm_wday=1, tm_yday=247, tm_isdst=0)3. 格式化时间(Format_string):
fmt1 =time.strftime('%H:%M:%S')   # 时分秒(全大写)
fmt2 =time.strftime('%Y-%m-%d')   # 年月日(年可大写可小写,月日小写)
fmt3 =time.strftime('%y-%m-%d')   # 年月日
fmt4 =time.strftime('%c')         # 本地相应的日期表示和时间表示print(fmt1)  # 16:49:03
print(fmt2)  # 2018-09-04
print(fmt3)  # 18-09-04
print(fmt4)  # Tue Sep  4 16:49:03 2018

 

3、几种时间格式间的转换

1. 转换

Timestamp ---> struct_time: time.localtime(转成我国的时间)、time.gmtime(转成伦敦时间)
struct_time ---> Timestamp: time.mktime()

Format_string ---> struct_time: time.strptime()
struct_time ---> Format_string: time.strftime()

 

2. 例子

1. 把格式化时间2018年8月8日转成时间戳时间
str_time = '2018-8-8'
struct_time = time.strptime(str_time,'%Y-%m-%d')
print(struct_time)  # time.struct_time(tm_year=2018, tm_mon=8, tm_mday=8, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=220, tm_isdst=-1)
timestamp = time.mktime(struct_time)
print(timestamp)   # 1533657600.02. 把时间戳时间转成格式化时间
timestamp = 1500000000
struct_time = time.localtime(timestamp)
str_time = time.strftime('%Y-%m-%d',struct_time)
print(str_time)   # 2017-07-143. 写函数,计算本月1号的时间戳时间
通过我拿到的这个时间,能迅速的知道我现在所在时间的年 月
def get_timestamp():str_time = time.strftime('%Y-%m-1')struct_time = time.strptime(str_time,'%Y-%m-%d')timestamp = time.mktime(struct_time)return timestamp
ret = get_timestamp()
print(ret)

 

%y 两位数的年份表示(00-99%Y 四位数的年份表示(0000-9999%m 月份(01-12%d 月内中的一天(0-31%H 24小时制小时数(0-23%I 12小时制小时数(01-12%M 分钟数(00-59%S 秒(00-59%a 本地简化星期名称%A 本地完整星期名称%b 本地简化的月份名称%B 本地完整的月份名称%c 本地相应的日期表示和时间表示%j 年内的一天(001-366%p 本地A.M.或P.M.的等价符%U 一年中的星期数(00-53)星期天为星期的开始%w 星期(0-6),星期天为星期的开始%W 一年中的星期数(00-53)星期一为星期的开始%x 本地相应的日期表示%X 本地相应的时间表示%Z 当前时区的名称%% %号本身
3. python中时间日期格式化符号

 

二、datetime模块

1、dateime.date

import datetime1. datetime.date类型(年月日)
注意:datetime.date类型就是time模块的结构化时间,只是它在内部把结构化时间的显示格式化了再打印出来
datetime.date.today()
datetime.date(2018, 12, 21)2.根据给定的时间戮,返回一个date对象
datetime.date.fromtimestamp(timestamp)  # 返回一个date对象,与datetime.date.today()作用相同
datetime.date.fromtimestamp(1528345678)  # 2018-06-073.由date日期格式转化为字符串格式
datetime.date.strftime(format)datetime.date.today().strftime('%Y-%m-%d')  # "2018-12-21"
注意:date类型没有strptime

 

2、datetime.dateime

注意:datetime是继承了date的类
1. datetime.datetime类型(年月日时分秒微妙时区)
datetime.datetime.today() 
datetime.datetime.now()datetime.datetime(2018,12, 21, 8, 12, 8, 603000)返回当前日期时间的日期部分
datetime.datetime.today().date()  # 2018-12-21
返回当前日期时间的时间部分
datetime.datetime.now().time()  # 15:19:16.2304492.根据给定的时间戮,返回一个datetime对象
datetime.datetime.fromtimestamp()  # 返回一个datetime对象,与datetime.datetime.today()作用相同
datetime.datetime.fromtimestamp(1528345678)  # 2018-06-07 12:27:583. 由日期格式转化为字符串格式
datetime.datetime.strftime(format)
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # "2018-12-21 09:17:14"3.由字符串格式转化为日期格式
datetime.datetime.strptime()
datetime.datetime.strptime('2018-12-21 11:01:27', '%Y-%m-%d %H:%M:%S')4. 结构化时间:元组
注意:这就是结构化时间初始的样子
datetime.datetime.now().timetuple()
# time.struct_time(tm_year=2018, tm_mon=12, tm_mday=21, tm_hour=9, tm_min=18, tm_sec=1, tm_wday=4, tm_yday=355, tm_isdst=-1)

 

3、datetime.timedelta

datetime.timedelta用于计算两个日期之间的差值datetime.timedelta(weeks=1)  # 返回一个时间差,参数weeks,days,hours,minutes,[1 weeks=7 days],没有years,months

例1:
import datetime
day7 = datetime.timedelta(days=7)  # 7天的时间时间隔  一年用52周表示 weeks=52
today = datetime.datetime.now()
# 7天之后的时间是什么
# today + 7
after_7 = today + day7
print(after_7, type(after_7))例2:
a=datetime.datetime.now()  # datetime.datetime(2018, 12, 21, 13, 15, 20, 871000)
b=datetime.datetime.now()  # datetime.datetime(2018, 12, 21, 13, 15, 29, 603000)print(b-a)  # datetime.timedelta(0, 0, 8, 732000)
print((b-a).seconds)  # 8
print((b-a).total_seconds())  # 8.732
或者
time1 = datetime.datetime(2018, 12, 20)
time2 = datetime.datetime(2017, 11, 12)"""计算天数差值"""
print((time1-time2).days)"""计算两个日期之间相隔的秒数"""
print ((time1-time2).total_seconds())

 

4、datetime.time

time类有5个参数,datetime.time(hour,minute,second,microsecond,tzoninfo),返回08:29:301.datetime.time.replace()2.datetime.time.strftime(format):按照format格式返回时间3.datetime.time.tzname():返回时区名字4.datetime.time.utcoffset():返回时区的时间偏移量

 

三、时间工具dateutil

直接看例子感受时间工具的绝对时间relativedelta吧

from dateutil import relativedelta
import datetimenow = datetime.datetime.today()
print(now)  # 2018-12-21 15:47:31.005604# 下个月
next_month = now + relativedelta.relativedelta(months=1)
print(next_month)  # 2019-01-21 15:47:31.005604# 注意months和month的区别:
# months=1 表示在现在的日期基础上加一个月的时间
# months=-1表示在现在的日期基础上减一个月
# month=1 表示把现在的日期的月份设置为1月
# years, months, days, weeks, hours, minutes, seconds等也是跟对应的year,month,day,week...一样
set_month = now + relativedelta.relativedelta(month=1)
print(set_month)  # 2018-01-21 15:47:31.005604# 注意与datetime.timedelta区别:
# datetime.timedelta没有months和years参数
# 因此一个月用weeks=4表示,只能表示28天后,有偏差
next_month2 = now + datetime.timedelta(weeks=4)
print(next_month2)  # 2019-01-18 15:47:31.005604# 下个月加一周
next_month_week = now + relativedelta.relativedelta(months=1, weeks=1)
print(next_month_week)  # 2019-01-28 15:47:31.005604# 下个月加一周,上午10点
next_month_week_ten = now + relativedelta.relativedelta(months=1, weeks=1, hour=10)
print(next_month_week_ten)  # 2019-01-28 10:47:31.005604# 一年后的前一个月
next_year_premonth = now + relativedelta.relativedelta(years=1, months=-1)
print(next_year_premonth)  # 2019-11-21 15:47:31.005604

 

转载于:https://www.cnblogs.com/Zzbj/p/10156501.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/395663.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

redux扩展工具_用鸭子扩展您的Redux App

redux扩展工具How does your front-end application scale? How do you make sure that the code you’re writing is maintainable 6 months from now?您的前端应用程序如何扩展? 您如何确定您正在编写的代码从现在起6个月内可维护? Redux took the …

mac下源码安装redis

转载:http://www.jianshu.com/p/6b5eca8d908b 下载安装包 redis-3.0.7.tar.gz 官网地址:http://redis.io/download 解压:tar -zvxf redis-3.0.7.tar.gz 将解压后的文件夹放到 /usr/local目录下 编译测试:接下来在终端中切换到/usr/local/red…

代码扫描工具测试覆盖率工具

测试覆盖率工具转载于:https://www.cnblogs.com/vivian-test/p/5398289.html

php splqueue 5.5安装,解析PHP标准库SPL数据结构

SPL提供了双向链表、堆栈、队列、堆、降序堆、升序堆、优先级队列、定长数组、对象容器SplQueue 队列类进出异端&#xff0c;先进先出<?php $obj new SplQueue();//插入一个节点到top位置$obj->enqueue(1);$obj->enqueue(2);$obj->enqueue(3);/**SplQueue Object…

Beta阶段敏捷冲刺总结

设想和目标 1. 我们的软件要解决什么问题&#xff1f;是否定义得很清楚&#xff1f;是否对典型用户和典型场景有清晰的描述&#xff1f; 在最开始的时候我们就是为了解决集美大学计算机工程学院网页没有搜索引擎的问题。因为没有搜索引擎&#xff0c;在搜索内容时需要根据查找信…

c语言 二进制压缩算法_使用C ++解释的二进制搜索算法

c语言 二进制压缩算法by Pablo E. Cortez由Pablo E.Cortez 使用C 解释的二进制搜索算法 (Binary Search Algorithms Explained using C) Binary search is one of those algorithms that you’ll come across on every (good) introductory computer science class. It’s an …

【LATEX】个人版latex论文模板

以下是我的个人论文模板&#xff0c;运行环境为Xelatex(在线ide&#xff1a;Sharelatex.com) 鉴于本人常有插入程序的需求&#xff0c;故引用了lstlisting \RequirePackage{ifxetex} \ifxetex\documentclass[hyperref, UTF8, c5size, no-math, winfonts&#xff0c;a4paper]{ct…

初识virtual memory

一、先谈几个重要的东西 virtual memory是一个抽象概念&#xff0c;书上的原文是"an abstraction of main memory known as virtual memory"&#xff08;参考资料p776&#xff09;。那么什么是抽象概念。下面说说我个人对这个东西的理解。 所谓抽象概念是指抽象出来的…

java创建mysql驱动,JDBC之Java连接mysql实现增删改查

使用软件&#xff1a;mysql、eclipse链接步骤&#xff1a;1.注册驱动2.创建一个连接对象3.写sql语句4.执行sql语句并返回一个结果或者结果集5.关闭链接(一般就是connection、statement、setresult)这三个连接对象&#xff0c;关闭顺序一般是(setresult ---> statement …

算法第五章作业

1.你对回溯算法的理解&#xff08;2分&#xff09; 回溯法&#xff08;探索与回溯法&#xff09;是一种选优搜索法&#xff0c;又称为试探法&#xff0c;按选优条件向前搜索&#xff0c;以达到目标。但当探索到某一步时&#xff0c;发现原先选择并不优或达不到目标&#xff0c;…

c++编码风格指南_100%正确的编码样式指南

c编码风格指南Here are three links worth your time:这是三个值得您花费时间的链接&#xff1a; The 100% correct coding style guide (4 minute read) 100&#xff05;正确的编码样式指南( 阅读4分钟 ) I wrote a programming language. Here’s how you can, too (10 minu…

xp开机黑屏故障分析

今天装完xp系统之后&#xff0c;重启开机发现竟然黑屏了&#xff0c;查资料发现有很多用户在修改分辨率后&#xff0c;因显示器不支持修改后的分辨率&#xff0c;会出现电脑黑屏的情况。分辨率调高了&#xff0c;超出了屏幕的范围&#xff0c;肯定会黑屏&#xff0c;而且这个问…

应用程序图标_如何制作完美的应用程序图标

应用程序图标by Nabeena Mali通过Nabeena Mali 如何制作完美的应用程序图标 (How to Make the Perfect App Icon) With just 24 app icon slots on the first page of an iPhone home screen, or 28 if you have a fancy iPhone 7, creating the perfect app icon is a vital …

Luogu3702 SDOI2017 序列计数 矩阵DP

传送门 不考虑质数的条件&#xff0c;可以考虑到一个很明显的$DP:$设$f_{i,j}$表示选$i$个数&#xff0c;和$mod\ pj$的方案数&#xff0c;显然是可以矩阵优化$DP$的。 而且转移矩阵是循环矩阵&#xff0c;所以可以只用第一行的数字代替整个矩阵。当然了这道题$p \leq 100$矩阵…

java闰年的年份,Java案例-判断给定年份是闰年

专注学子高考志愿填报&#xff0c;分享你所不知道信息。Java案例-判断给定年份是闰年案例描述编写程序&#xff0c;判断给定的某个年份是否是闰年。闰年的判断规则如下&#xff1a;(1)若某个年份能被4整除但不能被100整除&#xff0c;则是闰年。(2)若某个年份能被400整除&#…

通过path绘制点击区域

通过path绘制点击区域 效果 源码 https://github.com/YouXianMing/Animations // // TapDrawImageView.h // TapDrawImageView // // Created by YouXianMing on 16/5/9. // Copyright © 2016年 YouXianMing. All rights reserved. //#import <UIKit/UIKit.h> #…

Raft与MongoDB复制集协议比较

在一文搞懂raft算法一文中&#xff0c;从raft论文出发&#xff0c;详细介绍了raft的工作流程以及对特殊情况的处理。但算法、协议这种偏抽象的东西&#xff0c;仅仅看论文还是比较难以掌握的&#xff0c;需要看看在工业界的具体实现。本文关注MongoDB是如何在复制集中使用raft协…

db2 前滚会话

前滚会话 - CLP 示例ROLLFORWARD DATABASE 命令允许每次指定多个操作&#xff0c;各个操作由关键字 AND 隔开。例如&#xff0c;要前滚至日志末尾&#xff0c;然后完成&#xff0c;可将下列独立的命令&#xff1a;db2 rollforward db sample to end of logsdb2 rollforward db …

史上最烂代码_历史上最大的代码库

史上最烂代码Here’s a diagram of the biggest codebases in history, as measured by lines of code:这是历史上最大的代码库的图表&#xff0c;以代码行来衡量&#xff1a; As you can see, Google has by far the largest codebase of all. And all 2 billion lines of co…

php添加jpeg,PHP-如何将JPEG图像保存为渐进JPEG?

我具有以下将JPEG保存为渐进JPEG的功能.它已保存,但不是渐进式JPEG.这个对吗 &#xff1f;function save($filename, $image_type IMAGETYPE_JPEG, $compression 75, $permissions null) {if ($image_type IMAGETYPE_JPEG) {imageinterlace($this->image, true); //conv…