数学建模之数据分析【二一】: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

相关文章

MyBatis Plus实现时间字段自动填充的完整方案

《MyBatisPlus实现时间字段自动填充的完整方案》在日常开发中,我们经常需要记录数据的创建时间和更新时间,传统的做法是在每次插入或更新操作时手动设置这些时间字段,这种方式不仅繁琐,还容易遗漏,... 目录前言解决目标技术栈实现步骤1. 实体类注解配置2. 创建元数据处理器3. 服务层代码优化填充机制详

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Python实现批量CSV转Excel的高性能处理方案

《Python实现批量CSV转Excel的高性能处理方案》在日常办公中,我们经常需要将CSV格式的数据转换为Excel文件,本文将介绍一个基于Python的高性能解决方案,感兴趣的小伙伴可以跟随小编一... 目录一、场景需求二、技术方案三、核心代码四、批量处理方案五、性能优化六、使用示例完整代码七、小结一、

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

Python中logging模块用法示例总结

《Python中logging模块用法示例总结》在Python中logging模块是一个强大的日志记录工具,它允许用户将程序运行期间产生的日志信息输出到控制台或者写入到文件中,:本文主要介绍Pyt... 目录前言一. 基本使用1. 五种日志等级2.  设置报告等级3. 自定义格式4. C语言风格的格式化方法

Python实现精确小数计算的完全指南

《Python实现精确小数计算的完全指南》在金融计算、科学实验和工程领域,浮点数精度问题一直是开发者面临的重大挑战,本文将深入解析Python精确小数计算技术体系,感兴趣的小伙伴可以了解一下... 目录引言:小数精度问题的核心挑战一、浮点数精度问题分析1.1 浮点数精度陷阱1.2 浮点数误差来源二、基础解决

Java实现在Word文档中添加文本水印和图片水印的操作指南

《Java实现在Word文档中添加文本水印和图片水印的操作指南》在当今数字时代,文档的自动化处理与安全防护变得尤为重要,无论是为了保护版权、推广品牌,还是为了在文档中加入特定的标识,为Word文档添加... 目录引言Spire.Doc for Java:高效Word文档处理的利器代码实战:使用Java为Wo