如何在python中将日期时间转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28154066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:48:51  来源:igfitidea点击:

How to convert datetime to integer in python

pythondatetimeintegerconverter

提问by Tomá? Konyárik

how can i convert YYYY-MM-DD hh:mm:ss format to integer in python? for example 2014-02-12 20:51:14 -> to integer.

如何在python中将YYYY-MM-DD hh:mm:ss格式转换为整数?例如 2014-02-12 20:51:14 -> 到整数。

i know how to convert only hh:mm:ss but not yyyy-mm-dd hh:mm:ss

我知道如何只转换 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)

采纳答案by ely

It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetimemodule (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp()).

这取决于整数应该编码的内容。您可以将日期转换为之前某个时间的毫秒数。人们经常在 1970 年 1 月 1 日凌晨 12:00 或 1900 等日期做这件事,并将时间测量为从该点开始的整数毫秒。该datetime模块(或其他类似的)将具有为你做这个功能:例如,你可以使用int(datetime.datetime.utcnow().timestamp())

If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:

如果您想对年、月和日进行语义编码,一种方法是将这些分量乘以足够大的数量级值,以将它们并列在整数位中:

2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)

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

E.g.

例如

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

If you also want minutes and seconds, then just include further orders of magnitude as needed to display the digits.

如果您还需要分钟和秒,则只需根据需要包含更多数量级以显示数字。

I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.

我在遗留系统中经常遇到第二种方法,尤其是从遗留 SQL 数据库中提取基于日期的数据的系统。

It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.

这是非常糟糕的。您最终编写了大量用于对齐日期、计算月份或日期偏移量的 hacky 代码,因为它们以整数格式显示(例如,当您通过 12 月时将月份重置为 1,然后增加年份值),以及用于整个转换为整数格式。

Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.

除非这样的约定存在于您正在处理的 API 的深层、低级和经过全面测试的部分中,以便每个使用数据的人都真正可以依靠这个整数表示及其所有辅助函数,那么您最终导致很多人到处重写基本的日期处理程序。

It's generally much better to leave the value in a date context, like datetime.date, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.

将值保留在日期上下文中通常要好得多,例如datetime.date,尽可能长的时间,以便对它的操作在自然的、基于日期的上下文中表示,而不是某个单独的开发人员个人对整数的修改.

回答by Chicrala

I think I have a shortcut for that:

我想我有一个捷径:

# 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'))

回答by Atta Jutt

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

将日期时间转换为整数时,必须记住数十、数百和数千....例如“2018-11-03”必须像 int 中的 20181103 因为你必须 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

同样的另一个例子,"2018-11-03 10:02:05" 必须像 int 中的 20181103100205

Explanatory Code

解释代码

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")))

General Function

一般功能

To avoid that doing manually use below function

为了避免手动使用以下功能

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))

回答by Alexandre Crivellaro

This in an example that can be used for example to feed a database key, I sometimes use instead of using AUTOINCREMENT options.

在一个可用于例如提供数据库键的示例中,我有时使用而不是使用 AUTOINCREMENT 选项。

import datetime 

dt = datetime.datetime.now()
seq = int(dt.strftime("%Y%m%d%H%M%S"))