再见Datetime! 这个Python日期库太神了!

Pendulum详解1——Pendulum库入门指南 - 时光的艺术 时间,是编程世界中不可或缺的元素。无论是事件调度、数据分析,还是用户界面的显示,时间都扮演着关键的角色。然而,在Python的标准库`datetime`中,我们经常面临繁琐的操作和限制。为了摆脱这些束缚,我们引入了一个更加强大和灵活的时间处理库——Pendulum。 阅读详情

 
大家好,我是菜鸟哥!

关于日期处理,Python 提供了很多的库,比如标准库 datetime、第三方库 dateutil、arrow 等等。这里介绍一个我个人最喜欢的库 pendulum,用起来可以说非常的方便,任何对日期的操作它都能满足。

在使用之前需要先安装,直接 pip install pendulum 即可。

下面来看一下用法,首先是 datetime, date, time 的创建。

import pendulum

dt = pendulum.datetime(
    2022, 3, 28, 20, 10, 30)
print(dt.__class__)
print(dt)
"""
<class 'pendulum.datetime.DateTime'>
2022-03-28T20:10:30+00:00
"""
# 创建的对象是 DateTime 类型
# 并且带有时区,默认是 UTC
# 我们可以换一个时区
dt = pendulum.datetime(
    2022, 3, 28, 20, 10, 30, tz="Asia/Shanghai")
print(dt)
"""
2022-03-28T20:10:30+08:00
"""

# 如果不想要时区,那么指定 tz=None
dt = pendulum.datetime(
    2022, 3, 28, 20, 10, 30, tz=None)
print(dt)
"""
2022-03-28T20:10:30
"""

# 然后是 date 的创建
d = pendulum.date(2022, 3, 28)
print(d.__class__)
print(d)
"""
<class 'pendulum.date.Date'>
2022-03-28
"""

# time 的创建
t = pendulum.time(20, 10, 30)
print(t.__class__)
print(t)
"""
<class 'pendulum.time.Time'>
20:10:30
"""

如果创建 datetime 时,时区默认是 UTC。如果不想要时区,或者希望时区是本地时区,那么 pendulum 还专门提供了两个方法。

import pendulum

# 创建 datetime 时设置为本地时区
# 还是调用了 pendulum.datetime 函数
# 但是 tz 被设置成了 pendulum.local_timezone()
dt = pendulum.local(
    2022, 3, 28, 20, 10, 30)
print(dt)
"""
2022-03-28T20:10:30+08:00
"""
print(pendulum.local_timezone())
"""
Timezone('Asia/Shanghai')
"""

# 创建 datetime 时不设置时区
# 内部也是调用了 pendulum.datetime 函数
# 但是 tz 为 None
dt = pendulum.naive(2022, 3, 28, 20, 10, 30)
print(dt)
"""
2022-03-28T20:10:30
"""

然后 pendulum 还提供了几个方法,比如创建当前的 datetime,date 等等。

import pendulum

# 创建当前的 datetime
# 默认是本地时区,但时区可以指定
dt = pendulum.now()
print(dt)
"""
2022-05-29T20:40:49.632182+08:00
"""

# 创建当前的 date,但返回的仍是 datetime
# 只不过时分秒均为 0,同样可以指定时区
dt = pendulum.today()
print(dt)
"""
2022-05-29T00:00:00+08:00
"""

# 获取明天对应的 date
# 返回的是 datetime,时分秒为 0
# 时区可以指定,默认是本地时区
dt = pendulum.tomorrow()
print(dt)
"""
2022-05-30T00:00:00+08:00
"""

# 获取昨天对应的 date
dt = pendulum.yesterday()
print(dt)
"""
2022-05-28T00:00:00+08:00
"""

我们还可以根据时间戳或者字符串来创建:

import pendulum

# 根据时间戳创建
dt1 = pendulum.from_timestamp(1653828466)
dt2 = pendulum.from_timestamp(1653828466,
                              tz=pendulum.local_timezone())
print(dt1)
print(dt2)
"""
2022-05-29T12:47:46+00:00
2022-05-29T20:47:46+08:00
"""

# 根据字符串创建
dt1 = pendulum.parse("2020-05-03 12:11:33")
dt2 = pendulum.parse("2020-05-03 12:11:33",
                     tz=pendulum.local_timezone())
print(dt1)
print(dt2)
"""
2020-05-03T12:11:33+00:00
2020-05-03T12:11:33+08:00
"""

datetime、date、time 的创建我们说完了,然后再来看看它们支持的操作,这也是最核心的部分。

cf4c2ae2ba31322995b3a05c67f46fc0.gif

datetime 相关操作

操作非常多,我们逐一介绍。

import pendulum

dt = pendulum.local(
    2022, 3, 28, 20, 10, 30)

# 获取 date 部分和 time 部分
print(dt.date())
print(dt.time())
"""
2022-03-28
20:10:30
"""

# 替换掉 dt 的某部分,返回新的 datetime
# 年月日时分秒、以及时区都可以替换
print(dt.replace(year=9999))
"""
9999-03-28T20:10:30+08:00
"""

# 转成时间戳
print(dt.timestamp())
"""
1648469430.0
"""

# 返回年、月、日、时、分、秒、时区
print(dt.year, dt.month, dt.day)
print(dt.hour, dt.minute, dt.second)
print(dt.tz)
"""
2022 3 28
20 10 30
Timezone('Asia/Shanghai')
"""

然后是生成字符串,pendulum.DateTime 对象可以转成各种格式的日期字符串。

import pendulum

dt = pendulum.local(
    2022, 3, 28, 20, 10, 30)

# 下面四个最为常用
print("datetime:", dt.to_datetime_string())
print("date:", dt.to_date_string())
print("time:", dt.to_time_string())
print("iso8601:", dt.to_iso8601_string())
"""
datetime: 2022-03-28 20:10:30
date: 2022-03-28
time: 20:10:30
iso8601: 2022-03-28T20:10:30+08:00
"""
# 当然还支持很多其它格式,不过用的不多
# 随便挑几个吧
print("atom:", dt.to_atom_string())
print("rss:", dt.to_rss_string())
print("w3c:", dt.to_w3c_string())
print("cookie:", dt.to_cookie_string())
print("rfc822:", dt.to_rfc822_string())
"""
atom: 2022-03-28T20:10:30+08:00
rss: Mon, 28 Mar 2022 20:10:30 +0800
w3c: 2022-03-28T20:10:30+08:00
rfc822: Mon, 28 Mar 22 20:10:30 +0800
"""

我们有时也需要判断当前日期是星期几、在当前这一年是第几天等等,pendulum 也已经帮我们封装好了。

import pendulum

dt = pendulum.local(
    2022, 3, 28, 20, 10, 30)

# 返回星期几
# 注意:星期一到星期天分别对应 1 到 7
print(dt.isoweekday())  # 1

# 返回一年当中的第几天
# 范围是 1 到 366
print(dt.day_of_year)  # 87

# 返回一个月当中的第几天
print(dt.days_in_month)  # 31

# 返回一个月当中的第几周
print(dt.week_of_month)  # 5

# 返回一年当中的第几周
print(dt.week_of_year)  # 13

# 是否是闰年
print(dt.is_leap_year())  # False

最后就是日期的运算,这是 pendulum 最为强大的地方,至于为什么强大,我们演示一下就知道了。

import pendulum

dt = pendulum.local(
    2022, 3, 30, 20, 10, 30)

# 返回下一个月的今天
print(dt.add(months=1))
"""
2022-04-30T20:10:30+08:00
"""

# 返回上一个月的今天
# 但是上一个月是 2 月,并且是平年
# 所以最多 28 天
print(dt.add(months=-1))
"""
2022-02-28T20:10:30+08:00
"""
# 我们看到处理的非常完美
# 该方法的原型如下,年月日时分秒都是支持的,当然还有星期也支持
"""
def add(
    self,
    years=0,
    months=0,
    weeks=0,
    days=0,
    hours=0,
    minutes=0,
    seconds=0,
    microseconds=0,
):
"""

像 Python 的内置模块 datetime 在将日期相加的时候,最多支持到天,我们无法计算下一周、下一个月、下一年的日期。而 pendulum 则可以很方便地处理,这也是我最喜欢的一点。

当然啦,add 里面的值为正,相当于日期往后退;值为负,相当于日期往前推。

然后是两个日期还可以做减法:

import pendulum

dt1 = pendulum.local(
    2021, 1, 20, 11, 22, 33)

dt2 = pendulum.local(
    2022, 3, 30, 20, 10, 30)

period = dt2 - dt1
# 返回的是 Period 对象
# 相当于 datetime 模块里面的 timedelta
print(period.__class__)
"""
<class 'pendulum.period.Period'>
"""

# 但是功能方面,Period 要强大很多
# 两者差了多少年
print(period.in_years())  # 1
# 两者差了多少个月
print(period.in_months())  # 14
# 两者差了多少个星期
print(period.in_weeks())  # 62
# 两者差了多少天
print(period.in_days())  # 434
# 两者差了多少个小时
print(period.in_hours())  # 10424
# 两者差了多少分钟
print(period.in_minutes())  # 625487
# 两者差了多少秒
print(period.in_seconds())  # 37529277

功能非常强大,Python 的 datetime 模块里面的 timedelta 最多只能计算两个日期差了多少天,而这里年月日时分秒均可。

以上就是本文的内容,当然 pendulum 的功能其实不止我们上面说的那些,有兴趣的话可以参考官网,但常用的差不多就这些东西。


 

 
推荐阅读:
入门: 最全的零基础学Python的问题  | 零基础学了8个月的Python  | 实战项目 |学Python就是这条捷径
干货:爬取豆瓣短评,电影《后来的我们》 | 38年NBA最佳球员分析 |   从万众期待到口碑扑街!唐探3令人失望  | 笑看新倚天屠龙记 | 灯谜答题王 |用Python做个海量小姐姐素描图 |碟中谍这么火,我用机器学习做个迷你推荐系统电影
趣味:弹球游戏  | 九宫格  | 漂亮的花 | 两百行Python《天天酷跑》游戏!
AI: 会做诗的机器人 | 给图片上色 | 预测收入 | 碟中谍这么火,我用机器学习做个迷你推荐系统电影
小工具: Pdf转Word,轻松搞定表格和水印! | 一键把html网页保存为pdf!|  再见PDF提取收费! | 用90行代码打造最强PDF转换器,word、PPT、excel、markdown、html一键转换 | 制作一款钉钉低价机票提示器! |60行代码做了一个语音壁纸切换器天天看小姐姐!|

年度爆款文案

点阅读原文,看30个Python视频案例!

Codex零基础速通:网页/CLI/插件三端实战指南 Codex并非传统代码补全工具,而是一种具备工程上下文理解能力的编程协作者,其核心是将自然语言指令转化为可执行、可验证、带异常处理的完整脚本。它基于大语言模型原理,通过任务驱动式推理实现从需求到落地的端到端闭环,在数据采集、自动化运维、本地开发提效等场景中展现出显著的技术价值。尤其对零基础学习者,Codex能有效降低‘第一行代码’心理门槛,将模糊需求(如价格监控、API文档生成)压缩为精准约束指令,并支持网页沙盒执行、CLI离线批量、VS Code实时协同三种主流工作流。本文聚焦真实业务闭环,覆盖15种经压 阅读详情

相关推荐

Python日期和时间处理库之pendulum使用详解

在处理日期和时间时,Python 标准库中的datetime模块虽然功能强大,但有时显得过于复杂且缺乏一些便捷功能。为了解决这些问题,Pendulum 库应运而生。Pendulum 是一个 Python 日期和时间处理库,它在datetime模块的基础上进行了扩展,提供了更加友好的 API 和更多的功能。本文将详细介绍 Pendulum 库,包括其安装方法、主要特性、基本和高级功能,以及实际应用场景,帮助全面了解并掌握该库的使用。

Rocky006的博客 1238

python中datetime.date类介绍

date类是一个日期类,由年、月、日组成。由于Python也是面向对象编程语言,所以针对类,就会有构造函数,该类的构造函数如下:  class datetime.date(year, month, day):  year : 表示年,范围[MINYEAR, MAXYEAR],即[1, 9999]  month : 表示月,范围[1, 12]  day :一月中第几天,最大值根据给定的yea

sunjinjuan的博客 7万+

树莓派4B没有serial0或ttyS0,serial0没有映射到ttyS0,serial0和serial1调换映射

环境: 树莓派4B,ubuntu mate20 现象 终端输入ls -l /dev,发现只有serial1->ttyAMA0,没有serial0页没有ttyS0,更没有二者的映射。网上很多方法都是树莓派3B和3B+的,我自己试过,不太适用于4B,下面的方法是4B的,我自己用是成功的。 解决方法 cd /boot/firmware sudo gedit config.txt 注意不是/boot下的config,而是/boot/firmware下的config 打开文件后,找到enable_uart=0

qq_41208487的博客 7892

python的datetime库使用详解

本章介绍python最具代表性的的时间日期库——datetime。datetime库功能较全,拥有许多其他日期时间库不具有的功能。

m0_71559726的博客 1万+

Unreal Engine开发:角色动画与状态机_动画混合:通过混合节点实现平滑动画过渡

动画混合是提升游戏动画质量的关键技术之一。Unreal Engine提供了多种混合节点,包括BlendSpace1D、Blend Two By Bool、Blend Two By Alpha和Sequencer,每种节点适用于不同的场景。通过合理使用这些节点,可以实现平滑、自然且高效的动画过渡效果。此外,遵循最佳实践和高级应用技巧,可以进一步优化动画质量和性能。希望本节内容对你在Unreal Engine中实现动画混合有所帮助,使你的游戏角色动作更加流畅和自然。

chenlz2007的博客 1247

YOLO26-seg分割优化:轻量化卷积魔改 | 新的partial convolution(PConv)结合C3k2 | CVPR2023

​​​​​摘要:本研究对Ultralytics YOLO26进行了全面分析,重点阐述了其关键架构改进及其在实时边缘目标检测中的性能基准测试。YOLO26于2025年9月发布,是YOLO系列最新、最先进的成员,专为在边缘及低功耗设备上实现高效、精确且易于部署的目标而构建。本文依次详述了YOLO26的架构创新,包括:移除了分布焦点损失(DFL);采用端到端的无NMS推理;集成了渐进损失(ProgLoss)与小目标感知标签分配(STAL);以及引入了用于稳定收敛的MuSGD优化器。

①答疑群聊服务;②YOLO大模型知识问答系统;③计算机视觉论文生成智能体; 153

pendulum,一个更好用的Python库!

你好,我是郭震今天,我们将深入了解一个相对不那么知名但功能强大的 Python 包:pendulum。这个包是一个处理日期和时间的库,它以简洁和易于理解的方式提供了比标准 datetime 模块更丰富、更人性化的接口。安装 Pendulum首先,我们需要通过 pip 安装 pendulum 包。打开你的终端或命令提示符,输入以下命令:pipinstallpendulum安装完成后,我们就可以开...

算法channel 347

《Python星球日记》 第73天:情感分析与主题建模

《Python星球日记》 第73天:情感分析与主题建模,今天我们将探索两个自然语言处理领域的重要技术:情感分析和主题建模。这两项技术在社交媒体分析、用户反馈处理、市场研究等多个领域有着广泛应用。

Code_流苏:在代码中寻诗意,在实践中觅真知 919

pendulum,一个超酷的 Python 库!

Pendulum 是一个 Python 库,旨在提供更直观和功能丰富的日期和时间操作功能。它建立在 Python 标准库中的datetime模块之上,提供了更多功能、更简单的 API,并解决了时区和日期时间算术等问题。Pendulum 的主要特点包括:直观的 API:Pendulum 提供了易于理解和使用的方法和属性,使日期和时间操作更加直观。时区感知:Pendulum 对时区的支持非常强大,可以轻松处理不同时区的日期和时间。不可变性。

涛哥聊Python 1559

YOLO26 vs YOLOv12 vs YOLOv10:工业场景性能实测,速度/精度/部署难度全对比(附完整测试代码)

YOLO26:工业场景全能型选手,无NMS+无DFL设计让部署和推理都省心,小目标精度优势明显,CPU推理速度提升43%,适合大多数生产线场景YOLOv12:中大型目标检测专家,Area Attention在复杂背景下表现出色,适合汽车、家电等大型零部件检测YOLOv10:速度狂魔,GPU上性能领先,轻量化版本适合边缘部署,但小目标精度略逊,适合对实时性要求极高的分拣线场景。

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 625

修改 Alist 密码时报错?看看这个坑怎么解决!

启动服务后,再修改密码”。以后再遇到类似问题,先检查服务是否正常运行,说不定就能少踩不少坑。如果还有其他 Alist 的问题,欢迎在评论区留言交流~

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 1155

手把手搭建教育数据分析管道:Python+SQLite+Airflow实战

数据管道是现代数据工作的基础设施,本质是将原始数据通过提取、清洗、标准化、存储与调度形成可复现、可验证、可维护的自动化流程。它解决的不是建模或算法问题,而是保障分析所用数据的真实性、时效性与一致性。掌握数据管道思维,意味着能快速应对政府公报PDF、统计年鉴Excel等多源异构数据的整合挑战,显著降低‘找数-拼数-验数’的重复成本。本文以教育GPA与家庭收入关联分析为真实场景,基于Python生态与轻量级技术栈(SQLite/Airflow),详解从零构建具备质量校验、名称标准化、增量更新能力的本地化数据管道

weixin_30374009的博客 318

Transformer实战(38)——视觉Transformer (Vision Transformer, ViT)

Transformer 在自然语言处理 (NLP) 领域取得了显著成就,在许多不同的任务中都表现出色。在本节中,我们将探索视觉 Transformer (Vision Transformer, ViT) 模型。正如 NLP 领域创建了多种模型一样,视觉领域也开发了多种模型,每种模型都为计算机视觉提供了新的视角。通过本节,将学习如何使用 ViT 等模型进行计算机视觉任务,了解基于 Transformer 的预训练计算机视觉模型的工作原理,以及如何针对特定任务进行微调。

盼小辉丶的博客 2921

Python标准库datetime库date类详解(2/6)

Date类用来专门处理日期如年、月、日相关的数据。

m0_73608980的博客 2581

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Pendulum时间戳转换终极指南:从Unix时间到DateTime的完整教程

在处理时间数据时,Unix时间戳转换是Python开发者经常遇到的挑战。Pendulum库为时间戳转换提供了简单直观的解决方案,让复杂的时区处理和格式转换变得轻而易举。本文将为你详细介绍如何使用Pendulum进行高效的时间戳转换操作。 ## 🔥 为什么选择Pendulum进行时间戳转换? 传统的Python `datetime`模块在处理时间戳时存在诸多限制,特别是涉及时区转换时。Pend

gitblog_01194的博客 1002

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Pendulum —— 一个专业的 Python 库

之前介绍时,有朋友留言提到 Arrow 的 “竞争者” Pendulum。它们都能很好地处理时间对象,但从专业性来说,Pendulum 更胜一筹,今天我们就来聊聊 pendulum。当你在处理日常编程任务时,是否经常被时间和日期的处理所困扰?是否曾试图找到一个既强大又简单的方法来处理各种时间问题,比如时区转换、时间差计算、或是日期格式化?而现在,有了 Pendulum,这些问题将不再是你的负担。

Python栈_基的博客 1516

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

datetime 模块详解 -- 基本的日期和时间类型

转自:https://www.cnblogs.com/fclbky/articles/4098204.html datetime 模块提供了各种类用于操作日期和时间,该模块侧重于高效率的格式化输出在 Python 中,与时间处理有关的模块包括:time,datetime 以及 calendardatetime 模块定义了两个常量: datetime.MINYEAR - date 和 dat...

weixin_30550081的博客 4123

python内置模块datetime.date类详细介绍

Python的datetime模块是一个强大的日期和时间处理库,它提供了多个类来处理日期和时间。主要包括几个功能类datetime.date、datetime.time、datetime.datetime、datetime.timedelta,datetime.timezone等。

kymppcds的博客 2038

python 菜鸟教程

输出指定格式的日期

fenxiang_Hao的博客 373

Python获取时间

方法将日期和时间对象格式化为指定的字符串格式,模块来获取当前的月份。函数获取当前的日期和时间信息,然后使用。属性获取当前的月份。返回当前的日期和时间,然后使用。属性提取当前的年份,月份,天。使用 Python 的。

biyn9的博客 381

Python Pendulum库:优雅的时间处理利器

Pendulum库以其简洁的API、强大的时区处理和灵活的时间计算功能,成为Python开发者在时间处理方面的得力助手。无论是处理日常的时间任务还是在复杂的项目中,Pendulum都能大大提高开发效率,让时间处理变得更加轻松。Pendulum提供了非常直观的方法来创建、操作和格式化时间对象。而Pendulum库的出现,为我们提供了一种更加优雅、简洁且强大的时间处理方式。可以方便地在不同时区之间进行时间转换,确保时间的准确性。允许进行链式操作,使得对时间对象的一系列操作可以连续进行,代码更加简洁流畅。

m0_46311182的博客 568

`Pendulum`: 掌握时间的艺术,让Python日期时间操作不再复杂

在Python开发中,处理日期和时间是一个常见但复杂的任务。datetime模块虽然功能强大,但使用起来不够直观。Pendulum库的出现,就是为了简化这一过程,它提供了更人性化的API来处理日期和时间。Pendulum是一个强大的Python库,它通过提供直观的API简化了日期和时间的操作。无论是处理时区、解析日期时间字符串,还是计算日期差异,Pendulum都能轻松应对。通过上述介绍,你应该能够掌握Pendulum的基本用法,并在实际项目中有效地使用它。

AIGC搞起 872

Python:pendulum库处理时间

文档 https://pendulum.eustace.io/docs/ 安装 pip install pendulum 代码示例 import pendulum # 1、获取时间 print(pendulum.now()) # 2019-12-12T15:52:35.837803+08:00 print(pendulum.today()) # 2019-12-12T00:00:00+08:...

彭世瑜的博客 4683
上一篇: 10大名场面!Python处理办公自动化的10招!
下一篇: 13个Python小游戏,可以上班摸鱼玩了一天
菜鸟学Python
博客等级 码龄9年 8086粉丝 571原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值