数学建模之数据分析【二一】:Python中基本日期时间操作

2024-08-26 13:36

本文主要是介绍数学建模之数据分析【二一】:Python中基本日期时间操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 一、datetime.date()
  • 二、datetime.time()
  • 三、datetime.datetime()
  • 四、datetime.timedelta()
  • 五、datetime.tzinfo()
  • 六、datetime.timezone()

公众号:快乐数模
小红书:学数模使我快乐

Python 有一个名为 DateTime 的内置模块,可以以多种方式处理日期和时间。在本文中,我们将了解 Python 中的基本 DateTime 操作。

datetime 模块中有六个主要对象类及其各自的组件,如下所示:

  • datetime.date
  • datetime.time
  • datetime.datetime
  • datetime.tzinfo
  • datetime.timedelta
  • datetime.timezone
    现在我们将看到上述 datetime 模块下每个函数的程序。

一、datetime.date()

我们可以从日期类生成日期对象。日期对象表示具有年、月、日的日期。

from datetime import datecurrent = date.today() # print current year, month, and year individually
print("Current Day is :", current.day)
print("Current Month is :", current.month)
print("Current Year is :", current.year)print("\n")
print("Let's print date, month and year in different-different ways")
format1 = current.strftime("%m/%d/%y")print("format1 =", format1)format2 =  current.strftime("%b-%d-%Y")
print("format2 =", format2)format3 = current.strftime("%d/%m/%Y")print("format3 =", format3)format4 =  current.strftime("%B %d, %Y")print("format4 =", format4)

在这里插入图片描述

二、datetime.time()

从时间类生成时间对象代表当地时间。

  • hour
  • minute
  • second
  • microsecond
  • tzinfo

语法:datetime.time(hour, minute, second, microsecond)

from datetime import time
defaultTime = time()print("default_hour =", defaultTime.hour)
print("default_minute =", defaultTime.minute)
print("default_second =", defaultTime.second)
print("default_microsecond =", defaultTime.microsecond)time1 = time(10, 5, 25)
print("time_1 =", time1)time2 = time(hour=10, minute=5, second=25)
print("time_2 =", time2)time3 = time(hour=10, minute=5, second=25, microsecond=55)
print("time_3 =", time3)

在这里插入图片描述

三、datetime.datetime()

datetime.datetime() 模块显示日期和时间的组合。

  • year
  • month
  • day
  • hour
  • minute
  • second,
  • microsecond
  • tzinfo
    语法:datetime.datetime( year, month, day) or datetime.datetime(year, month, day, hour, minute, second, microsecond)

使用strftime()以不同方法获得当前日期。
strftime(“%d”) 提供当前天数
strftime(“%m”) 提供当前月份
strftime(“%Y”) 提供当前年份
strftime(“%H:%M:%S”) 以小时、分钟、秒的格式提供当前日期
strftime(“%m/%d/%Y, %H:%M:%S”) 提供日期和时间

from datetime import datetime
#打印当前时间
current = datetime.now()
print(current)
print("\n")
print("print each term individually")
#打印当前天
day = current.strftime("%d")
print("day:", day)
#打印当前月
month = current.strftime("%m")
print("month:", month)
#打印当前年
year = current.strftime("%Y")
print("year:", year)
#打印当前的时分秒
time = current.strftime("%H:%M:%S")
print("time:", time)
#打印当前的月日年,时分秒
print("\n")
print("printing date and time together")
date_time = current.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:", date_time)
print("\n")
#打印时间戳,记录由时间戳到现在的值
timestamp = 1615797322
date_time = datetime.fromtimestamp(timestamp)
#表示使用本地设置的日期和时间的格式
time_1 = date_time.strftime("%c")
print("first_output:", time_1)
# 日期短格式
time_2 = date_time.strftime("%x")
print("second_output:", time_2)
#日期长格式
time_3 = date_time.strftime("%X")
print("third_output:", time_3)print("\n")
manual = datetime(2021, 3, 28, 23, 55, 59, 342380)
print("year =", manual.year)
print("month =", manual.month)
print("hour =", manual.hour)
print("minute =", manual.minute)
print("timestamp =", manual.timestamp())

在这里插入图片描述

四、datetime.timedelta()

它显示以微秒分辨率表达两个日期、时间或日期时间实例之间的差异的持续时间。

这里我们实现了一些基本功能,并打印了过去和未来的日期。此外,我们还将打印 timedelta max、min 和resolution 的其他一些属性,分别显示最大日期和时间、最小日期和时间以及不相等 timedelta 对象之间的最小可能差异。这里我们还将对两个不同的日期和时间应用一些算术运算。

from datetime import timedelta, datetimepresent_date_with_time = datetime.now()print("Present Date :", present_date_with_time)ten_days_after = present_date_with_time + timedelta(days=10)
print('Date after 10 days :', ten_days_after)ten_days_before = present_date_with_time - timedelta(days=10)
print('Date before 10 days :', ten_days_before)one_year_before_today = present_date_with_time + timedelta(days=365)
print('One year before present Date :', one_year_before_today)one_year_after_today = present_date_with_time - timedelta(days=365)
print('One year before present Date :', one_year_after_today)print("print some other attributes of timedelta\n")
print("Max : ", timedelta.max)
print("Min : ", timedelta.min)
print("Resolution: ", timedelta.resolution)
print('Total number of seconds in an year :',timedelta(days=365).total_seconds())
print("\nApply some operations on timedelta function\n")
time_after_one_min = present_date_with_time + timedelta(seconds=10) * 6
print('Time after one minute :', time_after_one_min)
print('Timedelta absolute value :', abs(timedelta(days=+20)))
print('Timedelta string representation :', str(timedelta(days=5,seconds=40, hours=20, milliseconds=355)))
print('Timedelta object representation :', repr(timedelta(days=5,seconds=40, hours=20, milliseconds=355)))

在这里插入图片描述

五、datetime.tzinfo()

时区信息对象的抽象基类。它们被 datetime 和 time 类用来提供可自定义的时间调整概念。
tzinfo 基类有以下四种方法:

  • utcoffset(self, dt):返回作为参数传递的 datetime 实例的偏移量
  • dst(self, dt): dst 代表夏令时。dst 表示在夏季将时钟拨快 1 小时,以便根据时钟黑夜来得更晚。它设置为开启或关闭。它根据以下元素进行检查:
    (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0)
  • tzname(self, dt):返回一个 Python 字符串对象。它用于查找传递的 datetime 对象的时区名称。
  • fromutc(self, dt) :此函数返回等效的本地时间,并采用 UTC 中的对象日期和时间。它主要用于调整日期和时间。它从默认的 datetime.astimezone() 实现中调用。dt.tzinfo 将作为 self 传递,dst 日期和时间数据将作为等效的本地时间返回。
    注意:如果 dt.tzinfo 不是自身或/且 dst() 为 None,则会引发 ValueError。
from datetime import datetime, timedelta
from pytz import timezone
import pytztime_zone = timezone('Asia/Calcutta')normal = datetime(2021, 3, 16)
ambiguous = datetime(2021, 4, 16, 23, 30)print("Operations on normal datetime")
print(time_zone.utcoffset(normal, is_dst=True))
print(time_zone.dst(normal, is_dst=True))
print(time_zone.tzname(normal, is_dst=True))print(time_zone.utcoffset(normal, is_dst=False))
print(time_zone.dst(normal, is_dst=False))
print(time_zone.tzname(normal, is_dst=False))print("\n")
print("Operations on ambiguous datetime")
print(time_zone.utcoffset(ambiguous, is_dst=True))
print(time_zone.dst(ambiguous, is_dst=True))
print(time_zone.tzname(ambiguous, is_dst=True))print(time_zone.utcoffset(ambiguous, is_dst=False))
print(time_zone.dst(ambiguous, is_dst=False))
print(time_zone.tzname(ambiguous, is_dst=False))

在这里插入图片描述

六、datetime.timezone()

描述:它是一个将 tzinfo 抽象基类实现为相对于 UTC 的固定偏移量的类。

语法: datetime.timezone()

from datetime import datetime, timedelta
from pytz import timezone
import pytzutc = pytz.utc
print(utc.zone)india = timezone('Asia/Calcutta')
print(india.zone)eastern = timezone('US/Eastern')
print(eastern.zone)time_format = '%Y-%m-%d %H:%M:%S %Z%z'loc_dt = india.localize(datetime(2021, 3, 16, 6, 0, 0))
loc_dt = india.localize(datetime(2021, 3, 16, 6, 0, 0))
print(loc_dt.strftime(time_format))eastern_dt = loc_dt.astimezone(eastern)
print(eastern_dt.strftime(time_format))print(datetime(2021, 3, 16, 12, 0, 0, tzinfo=pytz.utc).strftime(time_format))before_dt = loc_dt - timedelta(minutes=10)
print(before_dt.strftime(time_format))
print(india.normalize(before_dt).strftime(time_format))after_dt = india.normalize(before_dt + timedelta(minutes=20))
print(after_dt.strftime(time_format))

在这里插入图片描述

学习geeksforgeeks网站内容总结

这篇关于数学建模之数据分析【二一】:Python中基本日期时间操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1108713

相关文章

Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码

《Java中Date、LocalDate、LocalDateTime、LocalTime、时间戳之间的相互转换代码》:本文主要介绍Java中日期时间转换的多种方法,包括将Date转换为LocalD... 目录一、Date转LocalDateTime二、Date转LocalDate三、LocalDateTim

Linux ls命令操作详解

《Linuxls命令操作详解》通过ls命令,我们可以查看指定目录下的文件和子目录,并结合不同的选项获取详细的文件信息,如权限、大小、修改时间等,:本文主要介绍Linuxls命令详解,需要的朋友可... 目录1. 命令简介2. 命令的基本语法和用法2.1 语法格式2.2 使用示例2.2.1 列出当前目录下的文

Python 迭代器和生成器概念及场景分析

《Python迭代器和生成器概念及场景分析》yield是Python中实现惰性计算和协程的核心工具,结合send()、throw()、close()等方法,能够构建高效、灵活的数据流和控制流模型,这... 目录迭代器的介绍自定义迭代器省略的迭代器生产器的介绍yield的普通用法yield的高级用法yidle

使用Python将JSON,XML和YAML数据写入Excel文件

《使用Python将JSON,XML和YAML数据写入Excel文件》JSON、XML和YAML作为主流结构化数据格式,因其层次化表达能力和跨平台兼容性,已成为系统间数据交换的通用载体,本文将介绍如何... 目录如何使用python写入数据到Excel工作表用Python导入jsON数据到Excel工作表用

Mysql表如何按照日期字段的年月分区

《Mysql表如何按照日期字段的年月分区》:本文主要介绍Mysql表如何按照日期字段的年月分区的实现方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、创键表时直接设置分区二、已有表分区1、分区的前置条件2、分区操作三、验证四、注意总结一、创键表时直接设置分区

Python基础语法中defaultdict的使用小结

《Python基础语法中defaultdict的使用小结》Python的defaultdict是collections模块中提供的一种特殊的字典类型,它与普通的字典(dict)有着相似的功能,本文主要... 目录示例1示例2python的defaultdict是collections模块中提供的一种特殊的字

利用Python快速搭建Markdown笔记发布系统

《利用Python快速搭建Markdown笔记发布系统》这篇文章主要为大家详细介绍了使用Python生态的成熟工具,在30分钟内搭建一个支持Markdown渲染、分类标签、全文搜索的私有化知识发布系统... 目录引言:为什么要自建知识博客一、技术选型:极简主义开发栈二、系统架构设计三、核心代码实现(分步解析

基于Python实现高效PPT转图片工具

《基于Python实现高效PPT转图片工具》在日常工作中,PPT是我们常用的演示工具,但有时候我们需要将PPT的内容提取为图片格式以便于展示或保存,所以本文将用Python实现PPT转PNG工具,希望... 目录1. 概述2. 功能使用2.1 安装依赖2.2 使用步骤2.3 代码实现2.4 GUI界面3.效

Python获取C++中返回的char*字段的两种思路

《Python获取C++中返回的char*字段的两种思路》有时候需要获取C++函数中返回来的不定长的char*字符串,本文小编为大家找到了两种解决问题的思路,感兴趣的小伙伴可以跟随小编一起学习一下... 有时候需要获取C++函数中返回来的不定长的char*字符串,目前我找到两种解决问题的思路,具体实现如下:

python连接本地SQL server详细图文教程

《python连接本地SQLserver详细图文教程》在数据分析领域,经常需要从数据库中获取数据进行分析和处理,下面:本文主要介绍python连接本地SQLserver的相关资料,文中通过代码... 目录一.设置本地账号1.新建用户2.开启双重验证3,开启TCP/IP本地服务二js.python连接实例1.