即便是python资深用户也经常会错写datetime.strptime(string, format) ,颠倒两个参数的顺序而写成了datetime.strptime(format, string) ,与re.find(pattern, string)相混淆。

分析问题

1、datetime.strptime()

首先strptime的函数命名不太好, 词义模糊, 不如直接叫str2time。string是source,time是result。

strptime(string, format) method of builtins.type instance

string, format -> new datetime parsed from a string (like time.strptime())

#Case

In [6]: datetime.strptime("8 May, 2019", "%d %B, %Y")

Out[6]: datetime.datetime(2019, 5, 8, 0, 0)

本函数的工作是parse a string to produce a time object。strptime 的字面含义读起来却像是毫无意义的string to parse time或者是读成相反的含义parse time to produce a string。妥协的处理方法理解为‘string parsed’ to time。将strp当做一个组合名词即strp2time。

官方的 strptime 命名比较 str2time 的优点是存在动词 parse, 点出函数的内部逻辑需要做的核心工作是解析。将普通的字符串解析成为有实际价值和意义的时间对象。(更像是开发者提醒自己非写给API的用户)

我们可以将参数名做简单的扩展:

datetime.strptime(string, format)

#扩展为

def strptime(src_string, parsed_format) -> "dst_time_object":

这样看来strptime还是符合 source to destination 的模式。

容易混淆 string 与 format 顺序的一个直接原因是存在 re.match(pattern, str),按照module re的这个思路, 要事第一!对strptime(string, format)的处理似乎也应该将format拿到前面。

对此的理解:

1)source to destination 是惯例, strptime(string, format)没有打破惯。

2)regex 突破了惯例, 可能因为 consturct regex 需要花费较多脑力,而其他如time-format并不需要多少思考。(regex的所有的methods都是将构建regex-pattern作为第一个参数)

3)处理 strptime 从字面含义去引导直觉. strptime(string, parsed-format) to a time-object

2、datetime.strftime()

容易混淆的另外一个原因是strptime的逆函数strftime。

strftime(format)

format -> strftime() style string.

In [8]: dt

Out[8]: datetime.datetime(2019, 5, 8, 0, 0)

In [9]: dt.strftime("%d %B, %Y")

Out[9]: '08 May, 2019'

strftime是time2str。

上例中datetime_obj.strftime(format)是其对象式编程的写法,由于里面只有一个format参数,因而也往往容易诱导python用户在写strptime的时候也将format写在前面。

strftime的函数式写法为

In [9]: datetime.strftime(datetime.now(),"%b %d %Y %H:%M:%S")

Out[9]: 'Jun 11 2020 08:08:52'

这样一来与strptime函数就完全保持一致了,二者的参数都遵循 src to dst 的原则。

总结

1、二者的共性

使用strptime与strftime,直觉思考的时候首先从动词出发,分别从parse和format出发,并应用其函数式的完整参数模式,思考链条为:

parse -> parse src_string to dst_time

format -> format src_time to dst_string。

概括为以下三点:

辨析parse or format

都遵循 src to dst

str[pf]time顺序不变

2、特例与常规

除了re.search(pattern, src)之外,还有一个不守规矩的特例。

先看字符串的str.split函数

In [12]: "source to destination".split()

Out[12]: ['source', 'to', 'destination'] #遵循source to destination, convert src_str to dst_list

但是其逆操作却将要输出的结果放在了前面。

In [13]: " ".join(['source', 'to', 'destination'])

Out[13]: 'source to destination'

显然['source', 'to', 'destination'].join(" ")更为合理 convert src_list to dst_string

一种可能的解释,Python将所有涉及string的操作集中在了一处。

In [16]: len([m for m in dir(str) if not m.startswith("__")])

Out[16]: 45

In [17]: len([m for m in dir(list) if not m.startswith("__")])

Out[17]: 11

可以看到字符串str的方法整整是list的方法的四倍还多。

由此,我们辨析特例与常规:

regex.find 和 str.join 是特例,strptime, strftime, str.split是常规。

3、系统的date与clock服务

费这么多笔墨辨析strptime这一个函数,乃是因为维护系统的时间是操作系统最核心的基础服务之一。

$ date -u

$ sudo hwclock -u

2019-05-08 20:19:14.764965+08:00

#str2time, strptime

$ date -d "08 May 2019" +"%c"

Wed 08 May 2019 14:00:00 AM CST

#time2str, strftime

$ date +"%d %B, %Y"

08 May, 2019

#思路与strptime, strftime一致

盼本文对你有点滴启发有帮助。

文源网络,仅供学习之用,如有侵权请联系删除。

在学习Python的道路上肯定会遇见困难,别慌,我这里有一套学习资料,包含40+本电子书,800+个教学视频,涉及Python基础、爬虫、框架、数据分析、机器学习等,不怕你学不会!

https://shimo.im/docs/JWCghr8prjCVCxxK/ 《Python学习资料》

关注公众号【Python圈子】,优质文章每日送达。

python的datetime.strptime_Python中的时间函数datetime.strptime()参数顺序的问题相关推荐

  1. python使用statsmodels包中的tsaplots函数和lags参数可视化时间序列数据指定滞后位置个数(级别)以前的所有自相关性(plot the autocorrelation)

    python使用statsmodels包中的tsaplots函数和lags参数可视化时间序列数据指定滞后位置个数(级别)以前的所有自相关性(plot the autocorrelation Funct ...

  2. python使用statsmodels包中的tsaplots函数和lags参数可视化时间序列数据指定滞后位置个数(级别)以前的所有自相关性、自定义设置自相关图的标题、数据点的色彩

    python使用statsmodels包中的tsaplots函数和lags参数可视化时间序列数据指定滞后位置个数(级别)以前的所有自相关性.自定义设置自相关图的标题.数据点的色彩(plot the a ...

  3. Python中的时间函数datetime.timedelta()

    Python中的时间函数 时间上的加减 时间上的加减 getday() 返回在某年某月某日的基础上加n天后的年月日 import datetime import json import random ...

  4. python时间函数报错_python3中datetime库,time库以及pandas中的时间函数区别与详解...

    1介绍datetime库之前 我们先比较下time库和datetime库的区别 先说下time 在 Python 文档里,time是归类在Generic Operating System Servic ...

  5. python获取系统时间函数_python3中datetime库,time库以及pandas中的时间函数区别与详解...

    1介绍datetime库之前 我们先比较下time库和datetime库的区别 先说下time 在 Python 文档里,time是归类在Generic Operating System Servic ...

  6. 如何在函数式编程中存在时间函数?

    本文翻译自:How can a time function exist in functional programming? I've to admit that I don't know much ...

  7. python使用matplotlib可视化、使用annotate函数以及arrowprops参数在可视化图像中添加箭头和文本注释(arrow and text annotation)

    python使用matplotlib可视化.使用annotate函数以及arrowprops参数在可视化图像中添加箭头和文本注释(arrow and text annotation) 目录

  8. python使用statsmodels包中的tsaplots函数可视化时间序列数据所有滞后位置个数(级别)的自相关性(plot the autocorrelation function)

    python使用statsmodels包中的tsaplots函数可视化时间序列数据所有滞后位置个数(级别)的自相关性(plot the autocorrelation function) 目录

  9. python使用statsmodels包中的adfuller函数执行增强迪基-福勒检验(ADF检验、augmented Dickey-Fuller test)、判断时间序列数据是否平稳

    python使用statsmodels包中的adfuller函数执行增强迪基-福勒检验(ADF检验.augmented Dickey-Fuller test).判断时间序列数据是否平稳(station ...

最新文章

  1. hdu 1394(树状数组求逆序数)
  2. Exploiting the Syntax-Model Consistency for Neural Relation Extraction-学习笔记
  3. jqgrid mysql 分页_jQgrid 分页显示
  4. 重复包含定义 导致未定义类型不识别错误
  5. Linux部署SSM项目
  6. nginx流媒体服务器性能,搭建nginx流媒体服务器(支持HLS)
  7. ISO26262道路车辆功能安全标准-(1)适用范围
  8. [golang] 导入 go-sqlite3 报错解决方法
  9. 计算机弹音乐百度百科,电子音乐合成器
  10. 实验有效的js原生前端 全国三级联动
  11. DVD区域码相关知识
  12. Git是什么?有什么用?
  13. OpenCV Mat转dlib array2d
  14. 网站安全监控的意义何在?
  15. Word for mac V16.10中文版
  16. 中国石油大学(北京)《机械制造基础》第三次作业
  17. 职场情感录:办公室人际问题化解大法
  18. opensuse 软件源
  19. 9成企业打算发年终奖,人均到手2.3万元
  20. 2022.10.EEP開發筆記-1

热门文章

  1. PAT乙级 1018 锤子剪刀布
  2. 初中生游戏成瘾,严重影响学习成绩,家长该怎么办?
  3. win8系统wifi链接不上服务器,win8无线网络连接不上怎么解决
  4. Dart语法篇之面向对象继承和Mixins(六)
  5. 牛客编程巅峰赛:Tree III(BFS or DFS)
  6. 2018美国专利机构榜单:IBM蝉联榜首 华为京东方进前20
  7. 一个中年程序员学习中国近代史的小结
  8. 使用 SSL 加密的 JDBC 连接 SAP HANA 数据库
  9. C++之string长度
  10. Tomcat AJP 文件包含漏洞(CVE-2020-1938)