📌  相关文章
📜  如何在Python中将 DateTime 转换为整数

📅  最后修改于: 2022-05-13 01:55:16.024000             🧑  作者: Mango

如何在Python中将 DateTime 转换为整数

Python提供了一个名为 DateTime 的模块来执行所有与日期和时间相关的操作。它有一组丰富的函数,用于执行几乎所有与时间有关的操作。使用函数需要先导入, Python自带的,不需要单独安装。

在这里,我们处理一个特殊的日期对象。所以要将给定的日期转换为整数,我们可以按照以下方法进行。

方法 1:使用 100 的乘法

在此方法中,我们将日期的每个分量乘以 100 的倍数,然后将它们全部相加以将它们转换为整数。

Python3
# importing the datetime module
import datetime
 
# Getting todays date and time using now() of
# datetime class
current_date = datetime.datetime.now()
 
# Printing the current_date as the date object itself.
print("Original date and time object:", current_date)
 
# Retrieving each component of the date
# i.e year,month,day,hour,minute,second and
# Multiplying with multiples of 100
# year - 10000000000
# month - 100000000
# day - 1000000
# hour - 10000
# minute - 100
print("Date and Time in Integer Format:",
      current_date.year*10000000000 +
      current_date.month * 100000000 +
      current_date.day * 1000000 +
      current_date.hour*10000 +
      current_date.minute*100 +
      current_date.second)


Python3
# importing the datetime module
import datetime
 
# Getting todays date and time using now() of datetime
# class
current_date = datetime.datetime.now()
 
# Printing the current_date as the date object itself.
print("Original date and time object:", current_date)
 
# Using the strftime() of datetime class
# which takes the components of date as parameter
# %Y - year
# %m - month
# %d - day
# %H - Hours
# %M - Minutes
# %S - Seconds
print("Date and Time in Integer Format:",
      int(current_date.strftime("%Y%m%d%H%M%S")))


输出:

Original date and time object: 2021-08-10 15:51:25.695808
Date and Time in Integer Format: 20210810155125

方法 2:使用 datetime.strftime() 对象

在此方法中,我们使用了 datetime 类的 strftime()函数,该函数将其转换为可以使用 int()函数转换为整数的字符串。



代码:

蟒蛇3

# importing the datetime module
import datetime
 
# Getting todays date and time using now() of datetime
# class
current_date = datetime.datetime.now()
 
# Printing the current_date as the date object itself.
print("Original date and time object:", current_date)
 
# Using the strftime() of datetime class
# which takes the components of date as parameter
# %Y - year
# %m - month
# %d - day
# %H - Hours
# %M - Minutes
# %S - Seconds
print("Date and Time in Integer Format:",
      int(current_date.strftime("%Y%m%d%H%M%S")))

输出:

Original date and time object: 2021-08-10 15:55:19.738126
Date and Time in Integer Format: 20210810155519