Python日期和时间处理完全解读

本文概述

  • 滴答数
  • 例子
  • 如何获取当前时间?
  • 例子
  • 时间元组
  • 获取格式化时间
  • 例子
  • Python睡眠时间
  • 例子
  • 日期时间模块
  • 例子
  • 创建日期对象
  • 例子
  • 例子
  • 两个日期的比较
  • 例子
  • 日历模块
  • 例子
  • 打印全年日历
  • 例子
在实际的应用程序中, 有些情况下我们需要使用日期和时间。在python中有一些示例, 我们必须安排脚本在某些特定时间运行。
在python中, 日期不是数据类型, 但是我们可以通过导入以datetime, time和calendar命名的模块来使用date对象。
在本教程的这一部分中, 我们将讨论如何在python中使用日期和时间对象。
滴答数 在python中, 从1970年1月1日凌晨12点开始计时。模块时间的函数time()返回自1970年1月1日凌晨12点以来花费的滴答声总数。滴答声可以看作是最小的单位测量时间。
考虑以下示例。
例子
import time; #prints the number of ticks spent since 12 AM, 1st January 1970print(time.time())

【Python日期和时间处理完全解读】输出
1545124460.9151757

如何获取当前时间? 时间模块的localtime()函数用于获取当前时间元组。考虑以下示例。
例子
import time; #returns a time tuple print(time.localtime(time.time()))

输出
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=18, tm_hour=15, tm_min=1, tm_sec=32, tm_wday=1, tm_yday=352, tm_isdst=0)

时间元组 时间被视为9个数字的元组。让我们看一下时间元组的成员。
Index Attribute Values
0 Year 4位数字(例如2018)
1 Month 1至12
2 Day 1至31
3 Hour 0至23
4 Minute 0至59
5 Second 0至60
6 弱日 0至6
7 一年中的一天 1至366
8 Daylight savings -1、0、1或-1
获取格式化时间 可以使用时间模块的asctime()函数来格式化时间。它返回经过的时间元组的格式化时间。
例子
import time; #returns the formatted timeprint(time.asctime(time.localtime(time.time())))

输出
Tue Dec 18 15:31:39 2018

Python睡眠时间 时间模块的sleep()方法用于在给定的时间内停止脚本的执行。输出将延迟指定为float的秒数。
考虑以下示例。
例子
import time for i in range(0, 5): print(i) #Each element will be printed after 1 second time.sleep(1)

输出
0 1 2 3 4

日期时间模块 datetime模块使我们能够创建自定义日期对象, 对日期执行各种操作, 例如比较等。
要使用日期作为日期对象, 我们必须将datetime模块导入python源代码。
考虑以下示例, 以获取当前时间的datetime对象表示形式。
例子
import datetime; #returns the current datetime object print(datetime.datetime.now())

输出
2018-12-18 16:16:45.462778

创建日期对象 我们可以通过在要为其创建日期对象的datetime构造函数中传递所需的日期来创建日期对象。
考虑以下示例。
例子
import datetime; #returns the datetime object for the specified dateprint(datetime.datetime(2018, 12, 10))

输出
2018-12-10 00:00:00

我们还可以指定时间和日期, 以创建datetime对象。考虑以下示例。
例子
import datetime; #returns the datetime object for the specified timeprint(datetime.datetime(2018, 12, 10, 14, 15, 10))

输出
2018-12-10 14:15:10

两个日期的比较 我们可以使用> , > =, < 和< =等比较运算符来比较两个日期。
考虑以下示例。
例子
from datetime import datetime as dt #Compares the time. If the time is in between 8AM and 4PM, then it prints working hours otherwise it prints fun hours if dt(dt.now().year, dt.now().month, dt.now().day, 8)< dt.now()< dt(dt.now().year, dt.now().month, dt.now().day, 16): print("Working hours....") else: print("fun hours")

输出
fun hours

日历模块 Python提供了一个日历对象, 其中包含使用日历的各种方法。
考虑以下示例以打印2018年最后一个月的日历。
例子
import calendar; cal = calendar.month(2018, 12) #printing the calendar of December 2018 print(cal)

输出
Python日期和时间处理完全解读

文章图片
打印全年日历 日历模块的prcal()方法用于打印全年的日历。必须将要打印日历的年份传递给此方法。
例子
import calendar#printing the calendar of the year 2019 calendar.prcal(2019)

输出
Python日期和时间处理完全解读

文章图片

    推荐阅读