Python程序获取当前时间

There are different ways to get the current time in Python,

有多种获取Python当前时间的方法

1)使用时间模块获取当前时间 (1) Getting current time using time module)

Steps:

脚步:

  • Import the time module

    导入时间模块

  • Call the localtime() function of the time class – assign it in its object.

    调用时间类的localtime()函数-在其对象中分配它。

  • Format the time using strftime() function.

    使用strftime()函数格式化时间。

# Python program to get current time

# importing the time module
import time

# getting the current time
time_object = time.localtime()

# format the time 
current_time = time.strftime("%H:%M:%S", time_object)

# print the time 

print("Current time is: ", current_time)

Output

输出量

Current time is:  08:04:32

2)使用datetime对象获取当前时间 (2) Getting current time using datetime object)

Steps:

脚步:

  • Import the datetime class from datetime module

    从datetime模块导入datetime类

  • Call the now() function of datetime class

    调用datetime类的now()函数

  • Pass the object in the strftime() function to format the time

    在strftime()函数中传递对象以格式化时间

  • Print the time

    打印时间

# Python program to get current time

# importing the datetime class
# from datetime module
from datetime import datetime

# calling the now() function
obj_now = datetime.now()

# formatting the time
current_time = obj_now.strftime("%H:%M:%S")
print("Current time is:", current_time)

Output

输出量

Current time is: 08:08:53

3)获取不同时区的当前时间 (3) Getting current time of different time zones)

Steps:

脚步:

  • Import the datetime class from datetime module

    从datetime模块导入datetime类

  • Importing the pytz module to access date time from a specified time zone

    导入pytz模块以从指定时区访问日期时间

  • Using timezone() function of pytz module – we can specify the time zone, using "now()" function – we can access the current time and using strftime() function – we can format the time.

    使用pytz模块的timezone()函数–我们可以指定时区,使用“ now()”函数–我们可以访问当前时间,使用strftime()函数–我们可以格式化时间。

  • Print the time

    打印时间

# Python program to get current time

# importing the datetime class from 
# datetime module
from datetime import datetime
# importing the pytz 
import pytz

# specifying the indian time zoe 
tz_IN = pytz.timezone('Asia/Calcutta') 
datetime_IN = datetime.now(tz_IN)
print("Asia/Calcutta time is: ", datetime_IN.strftime("%H:%M:%S"))

# specifying the America/Chicago time zone
tz_Chicago = pytz.timezone('America/Chicago')
datetime_Chicago = datetime.now(tz_Chicago)
print("America/Chicago time is: ", datetime_Chicago.strftime("%H:%M:%S")) 

Output

输出量

Asia/Calcutta time is:  13:55:15
America/Chicago time is:  03:25:15


翻译自: https://www.includehelp.com/python/program-to-get-current-time.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值