GVKun编程网logo

python'x days ago'到datetime

12

在这篇文章中,我们将为您详细介绍python'xdaysago'到datetime的内容。此外,我们还会涉及一些关于datetime.datetime.strptime在Python2.4.1中不存在

在这篇文章中,我们将为您详细介绍python'x days ago'到datetime的内容。此外,我们还会涉及一些关于datetime.datetime.strptime在Python 2.4.1中不存在、Jquery Datetimepicker到Python Datetime、python date 和 datetime 的取值范围(对比 Mysql 的 datetime 和 timestamp)、python datetime 时区(timezone) dateutil的知识,以帮助您更全面地了解这个主题。

本文目录一览:

python'x days ago'到datetime

python'x days ago'到datetime

我有显示以下格式的日期的字符串:

x minutes/hours/days/months/years ago

我需要使用python将其解析为日期时间。

看来dateutil无法做到。

有办法吗?

答案1

小编典典

当然可以。您只需要一个timedelta

s = "3 days ago"parsed_s = [s.split()[:2]]time_dict = dict((fmt,float(amount)) for amount,fmt in parsed_s)dt = datetime.timedelta(**time_dict)past_time = datetime.datetime.now() - dt

顺便说一句,它看起来像dateutila
relativedelta,其行为类似于timedelta,但是构造函数也接受monthsyears在参数中(显然,参数必须是整数)。

datetime.datetime.strptime在Python 2.4.1中不存在

datetime.datetime.strptime在Python 2.4.1中不存在

在某些情况下,我们的团队需要使用Python 2.4.1。在Python
2.4.1strptime中的datetime.datetime模块中不存在:

Python 2.4.1 (#65,Mar 30 2005,09:13:57) [MSC v.1310 32 bit (Intel)]
Type "help","copyright","credits" or "license" for more information.
>>> import datetime
>>> datetime.datetime.strptime
Traceback (most recent call last):
  File "<string>",line 1,in <fragment>
AttributeError: type object 'datetime.datetime' has no attribute 'strptime'

与2.6相反:

Python 2.6.6 (r266:84297,Aug 24 2010,18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help","credits" or "license" for more information.
>>> import datetime
>>> datetime.datetime.strptime
<built-in method strptime of type object at 0x1E1EF898>

键入时,我在2.4.1的时间模块中找到了它:

Python 2.4.1 (#65,09:16:17) [MSC v.1310 32 bit (Intel)]
Type "help","credits" or "license" for more information.
>>> import time
>>> time.strptime
<built-in function strptime>

我认为它strptime在某个时候动了吗?检查这种事情的最好方法是什么。我尝试查看python的发行历史,但找不到任何东西。

Jquery Datetimepicker到Python Datetime

Jquery Datetimepicker到Python Datetime

我在jQuery Datetimepicker下面

<input type="text" name="datetime" id="datetime">
$("#datetime").datetimepicker({
    controlType: 'select',oneLine: true,timeFormat: 'hh:mm tt'
});

我将日期作为AJAX POST请求发送给Django:

const starts = $('#datetime').val();
$.ajax({
    type: 'POST',url: '/booking/new/',data: {
        starts: starts,},};

在Django我得到的价值:

if request.method == 'POST':
    starts = request.POST.get('starts')
    object.starts = datetime.strptime(starts,'%x %I:%M %p')

我收到以下错误:

ValueError: time data ’11/12/2016 12:00 am’ does not match format ‘%x %I:%M %p’

我尝试了不同的格式,但我找不到正确的格式.我可以从字符串值生成格式如何?

解决方法

您可以在 this之后定义默认日期时间格式,如 this

python date 和 datetime 的取值范围(对比 Mysql 的 datetime 和 timestamp)

python date 和 datetime 的取值范围(对比 Mysql 的 datetime 和 timestamp)

Python 的情况

先来看看 date 类型吧!

In [1]: from datetime import date

In [2]: date.min
Out[2]: datetime.date(1, 1, 1)

In [3]: str(date.min)
Out[3]: ''0001-01-01''

In [4]: str(date.max)
Out[4]: ''9999-12-31''

可以看到 python 的 date 的取值范围是 0001-01-019999-12-31

再来看看 datetime 吧!

In [5]: from datetime import datetime

In [6]: str(datetime.min)
Out[6]: ''0001-01-01 00:00:00''

In [7]: str(datetime.max)
Out[7]: ''9999-12-31 23:59:59.999999''

可以看到 python 的 datetime 的取值范围是 0001-01-01 00:00:009999-12-31 23:59:59.999999

Mysql 的情况

来看看 mysql 的情况吧,下面的官方文档中的内容:

The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in ''YYYY-MM-DD'' format. The supported range is ''1000-01-01'' to ''9999-12-31''.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ''YYYY-MM-DD hh:mm:ss'' format. The supported range is ''1000-01-01 00:00:00'' to ''9999-12-31 23:59:59''.

The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of ''1970-01-01 00:00:01'' UTC to ''2038-01-19 03:14:07'' UTC.

总结一下就是:

  • date 的取值范围:1000-01-019999-12-31
  • timestamp 的取值范围:1970-01-01 00:00:012038-01-19 03:14:07
  • datetime 的取值范围:1000-01-01 00:00:009999-12-31 23:59:59

参考资料:mysql 文档

但是需要注意:

Invalid DATE, DATETIME, or TIMESTAMP values are converted to the “zero” value of the appropriate type (''0000-00-00'' or ''0000-00-00 00:00:00''), if the SQL mode permits this conversion. The precise behavior depends on which if any of strict SQL mode and the NO_ZERO_DATE SQL mode are enabled; see Section 5.1.10, “Server SQL Modes”.

还有这部分:
图片.png

翻译成人话的意思,就是 myql 会把无效的 date 设为 0000-00-00,无效的 datetime 和 timestamp 设为 0000-00-00 00:00:00

比如 2022-13-35 就是一个无效的 date,当把这个值插入到 mysql 中的时候,开启了严格模式的 mysql 会报错,未开启严格模式的 mysql 会转为 0000-00-00 保存。

‼️ 所以我们使用 Python 从 mysql 读取时间类型的时候,一定要注意这个坑!因为 0000-00-00 没有办法转成 Python 的 date 类型,会报错的!‼️


顺便可以看看 Mysql 的 date、timestamp、datetime 各占用几个字节:

  • date 类型 3 字节
  • timestamp 类型 4 字节
  • datetime 类型 8 字节

图片.png

参考文章:Data Type Storage Requirements


关于 Mysql 插入的时间类型可以是 0000-00-00 这种格式的原因可以参考:MySQL Incorrect datetime value: ''0000-00-00 00:00:00''

在 Mysql8 中默认是不可以插入这种无效时间的

python datetime 时区(timezone) dateutil

python datetime 时区(timezone) dateutil

 

记录下python中的时区问题, 代码如下:

   包括datetime.datetime对象使用不同的时区,以及在不同时区间转换。

 1 from datetime import datetime
 2 
 3 from dateutil import tz, zoneinfo
 4 
 5 if __name__ == ''__main__'':
 6     zonefile = zoneinfo.get_zonefile_instance()
 7     print zonefile.zones.keys()[:20]
 8     # use timezone
 9     tz_dubai = tz.gettz(''Asia/Dubai'')
10     tz_sh = tz.gettz(''Asia/Shanghai'')
11     # Shanghai timezone
12     now_sh = datetime.now(tz=tz_sh)
13     print now_sh
14     # Dubai timezone
15     now_dubai = datetime.now(tz=tz_dubai)
16     print now_dubai
17     # datetime timezone conversion
18     print now_dubai.astimezone(tz_sh)
19     print ''done!''

结果:

[''Atlantic/Canary'', ''Europe/Lisbon'', ''Etc/GMT+9'', ''Etc/GMT+8'', ''Antarctica/Mawson'', ''Etc/GMT+3'', ''Etc/GMT+2'', ''Etc/GMT+1'', ''Etc/GMT+0'', ''Etc/GMT+7'', ''Etc/GMT+6'', ''Etc/GMT+5'', ''Etc/GMT+4'', ''Indian/Reunion'', ''America/Fort_Nelson'', ''Antarctica/Davis'', ''America/Coral_Harbour'', ''Asia/Dhaka'', ''America/St_Lucia'', ''Australia/LHI'']
2019-01-16 21:15:41.503000+08:00
2019-01-16 17:15:41.503000+04:00
2019-01-16 21:15:41.503000+08:00
done!

 

我们今天的关于python'x days ago'到datetime的分享就到这里,谢谢您的阅读,如果想了解更多关于datetime.datetime.strptime在Python 2.4.1中不存在、Jquery Datetimepicker到Python Datetime、python date 和 datetime 的取值范围(对比 Mysql 的 datetime 和 timestamp)、python datetime 时区(timezone) dateutil的相关信息,可以在本站进行搜索。

本文标签: