Python取当前时间精确到秒

Python取当前时间精确到秒

Python取当前时间精确到秒

在Python中,我们可以使用不同的方法来获取当前时间。而要将时间精确到秒,我们需要使用datetime模块来获得日期和时间的精确信息。下面将详细介绍如何在Python中取得当前时间并将其精确到秒。

导入模块

我们首先需要导入datetime模块。该模块包含了用于处理日期和时间的类和函数。

import datetime
Python

使用datetime模块获取当前时间

在获取当前时间之前,我们可能需要了解一些关于datetime模块的重要类。

datetime类

datetime类是datetime模块中的一个主要类,它可用于表示日期和时间对象。

datetime类的构造函数如下所示:

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
Python

参数说明:

  • year:年份,必需参数。
  • month:月份,取值范围为1到12。
  • day:日期,取值范围根据具体月份而不同。
  • hour:小时,默认为0。
  • minute:分钟,默认为0。
  • second:秒,默认为0。
  • microsecond:微秒,默认为0。
  • tzinfo:时区,默认为None。

获取当前时间

接下来,我们将使用datetime类的now()方法来获取当前时间。now()方法将返回一个表示当前本地时间的datetime对象。

示例代码如下:

import datetime

current_time = datetime.datetime.now()
print(current_time)
Python

示例运行结果:

2022-09-20 13:45:30.123456
Python

上述示例代码将打印当前本地时间,并将其精确到秒。

示例代码及运行结果

下面是五个示例代码,展示了如何取得当前时间并将其精确到秒。

示例1:以字符串格式输出当前时间

import datetime

current_time = datetime.datetime.now()
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_time)
Python

运行结果:

2022-09-20 13:45:30
Python

示例2:以时间戳格式输出当前时间

import datetime

current_time = datetime.datetime.now()
timestamp = current_time.timestamp()
print(timestamp)
Python

运行结果:

1668897930.123456
Python

示例3:以不同的格式输出当前时间

import datetime

current_time = datetime.datetime.now()
iso_format = current_time.isoformat()
print(iso_format)

formatted_time = current_time.strftime("%A, %B %d, %Y %I:%M%p")
print(formatted_time)

short_format = current_time.strftime("%m/%d/%Y, %H:%M:%S")
print(short_format)

custom_format = current_time.strftime("Today is %A, %B %d, %Y. Current time is %I:%M %p.")
print(custom_format)
Python

运行结果:

2022-09-20T13:45:30.123456
Tuesday, September 20, 2022 01:45PM
09/20/2022, 13:45:30
Today is Tuesday, September 20, 2022. Current time is 01:45 PM.
Python

示例4:获取当前时间的年、月、日、时、分、秒

import datetime

current_time = datetime.datetime.now()
year = current_time.year
month = current_time.month
day = current_time.day
hour = current_time.hour
minute = current_time.minute
second = current_time.second

print(year, month, day, hour, minute, second)
Python

运行结果:

2022 9 20 13 45 30
Python

示例5:计算当前时间与指定时间的时间差

import datetime

current_time = datetime.datetime.now()
specified_time = datetime.datetime(2022, 9, 10, 8, 30, 0)
time_difference = current_time - specified_time

print(time_difference)
Python

运行结果:

10 days, 5:15:30.123456
Python

总结

通过使用datetime模块,我们可以轻松地获取当前时间并将其精确到秒。我们可以将当前时间以不同的格式输出,计算时间差等。以上示例代码展示了一些常见的用法,帮助您更好地理解如何在Python中操作时间。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册