如何在Python中将
YYYY-MM-DD hh:mm:ss
格式转换为整数?
例如 2014-02-12 20:51:14
-> 为整数。
我只知道如何转换
hh:mm:ss
但不知道yyyy-mm-dd hh:mm:ss
def time_to_num(time_str):
hh, mm , ss = map(int, time_str.split(':'))
return ss + 60*(mm + 60*hh)
这取决于整数应该编码的内容。您可以将日期转换为之前某个时间的毫秒数。人们经常这样做,将时间固定在 1970 年 1 月 1 日或 1900 年等的凌晨 12:00,并以从该点开始的整数毫秒来测量时间。
datetime
模块(或其他类似模块)将具有为您执行此操作的函数:例如,您可以使用 int(datetime.datetime.utcnow().timestamp())
。
如果您想对年、月和日进行语义编码,一种方法是将这些分量乘以足够大的数量级值,以便将它们并列在整数数字中:
2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)
def to_integer(dt_time):
return 10000*dt_time.year + 100*dt_time.month + dt_time.day
例如
In [1]: import datetime
In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def to_integer(dt_time):
: return 10000*dt_time.year + 100*dt_time.month + dt_time.day
: # Or take the appropriate chars from a string date representation.
:--
In [3]: to_integer(datetime.date(2012, 6, 13))
Out[3]: 20120613
如果您还需要分钟和秒,则只需根据需要添加更多数量级即可显示数字。
我在遗留系统中经常遇到第二种方法,尤其是从遗留 SQL 数据库中提取基于日期的数据的系统。
这是非常糟糕。您最终会编写大量的 hacky 代码来对齐日期、计算月份或日期的偏移量(例如,当您经过 12 月时将月份重置为 1,然后增加年份值),以及用于完全在整数格式之间进行转换。
除非这样的约定存在于您正在使用的 API 的深层、低级且经过彻底测试的部分,这样每个使用数据的人都可以真正依赖这个整数表示及其所有辅助函数,那么最终,很多人都在重写基本的日期处理例程。
通常最好将值保留在日期上下文中,例如
datetime.date
,尽可能长时间保留,以便对其进行的操作在自然的、基于日期的上下文中表达,而不是某个单独开发人员的个人上下文破解一个整数。
我想我有一个捷径:
# Importing datetime.
from datetime import datetime
# Creating a datetime object so we can test.
a = datetime.now()
# Converting a to string in the desired format (YYYYMMDD) using strftime
# and then to int.
a = int(a.strftime('%Y%m%d'))
在一个可用于提供数据库密钥的示例中,我有时使用而不是使用 AUTOINCREMENT 选项。
import datetime
dt = datetime.datetime.now()
seq = int(dt.strftime("%Y%m%d%H%M%S"))
其他答案侧重于带有 int(mydate.strftime("%Y%m%d%H%M%S"))
的
人类可读表示。但这会让你失去很多,包括正常的整数语义和算术,因此我更喜欢类似 bash
date
's “自纪元(1970-01-01 UTC)以来的秒数”.
作为参考,您可以使用以下 bash 命令来获取
1392234674
结果:
date +%s --date="2014-02-12 20:51:14"
正如已接受的答案中ely暗示的那样,只是一个普通数字表示是明确无误的,并且更容易处理和解析,尤其是以编程方式。另外,从人类可读的格式到人类可读的格式的转换都是一个简单的单行文字。
datetime.timestamp()
,如 djvg 所评论的那样。对于其他方法,您可以考虑编辑历史记录。
这是一个简单的日期->第二个转换工具:
def time_to_int(dateobj):
total = int(dateobj.strftime('%S'))
total += int(dateobj.strftime('%M')) * 60
total += int(dateobj.strftime('%H')) * 60 * 60
total += (int(dateobj.strftime('%j')) - 1) * 60 * 60 * 24
total += (int(dateobj.strftime('%Y')) - 1970) * 60 * 60 * 24 * 365
return total
(实际上是一个 UNIX 时间戳计算器)
使用示例:
from datetime import datetime
x = datetime(1970, 1, 1)
time_to_int(x)
输出:0
x = datetime(2021, 12, 31)
time_to_int(x)
输出:1639785600
x = datetime(2022, 1, 1)
time_to_int(x)
输出:1639872000
x = datetime(2022, 1, 2)
time_to_int(x)
输出:1639958400
将日期时间转换为整数时,必须记住十、百和千......就像 “2018-11-03”必须类似于 int 中的 20181103 为此你必须 2018*10000+100*11+3
同样的另一个例子, “2018-11-03 10:02:05”必须类似于 int 中的 20181103100205
dt = datetime(2018,11,3,10,2,5)
print (dt)
#print (dt.timestamp()) # unix representation ... not useful when converting to int
print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100 + dt.day)
print (int(dt.strftime("%Y%m%d")))
print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000 + dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))
为避免手动使用以下功能
def datetime_to_int(dt):
return int(dt.strftime("%Y%m%d%H%M%S"))
df.Date = df.Date.str.replace('-', '').astype(int)
最直接的方法一定是
timestamp()
,它可用于日期时间并将任何日期时间转换为 POSIX 时间戳:
https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp
from datetime import datetime
s = "2014-02-12 20:51:14"
t = datetime.strptime(s, '%Y-%d-%m %H:%M:%S')
print(t.timestamp()) # outputs 1417549874.0