Python中的now()函数

Python库定义了一个函数,主要用于获取当前时间和日期。 现在() 函数返回当前本地日期和时间,该日期和时间在 datetime 单元

null

语法: 约会时间。现在(tz)

参数: 兹: 需要当前时间和日期的指定时区。(默认情况下使用格林威治子午线时间。)

返回: 以时间格式返回当前日期和时间。

代码#1:

# Python3 code to demonstrate
# Getting current time using
# now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print ( "Time now at greenwich meridian is : "
, end = "")
print (current_time)


输出:

Time now at greenwich meridian is : 2018-03-29 10:26:23.473031

now()的属性:

now()具有不同的属性,与时间属性相同,例如年、月、日期、小时、分钟、秒。

代码#2: 演示now()的属性。

# Python3 code to demonstrate
# attributes of now()
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing attributes of now().
print ( "The attributes of now() are : " )
print ( "Year : " , end = "")
print (current_time.year)
print ( "Month : " , end = "")
print (current_time.month)
print ( "Day : " , end = "")
print (current_time.day)
print ( "Hour : " , end = "")
print (current_time.hour)
print ( "Minute : " , end = "")
print (current_time.minute)
print ( "Second : " , end = "")
print (current_time.second)
print ( "Microsecond : " , end = "")
print (current_time.microsecond)


The attributes of now() are : 
Year : 2018
Month : 3
Day : 26
Hour : 20
Minute : 9
Second : 4
Microsecond : 499806

获取特定时区的时间:

有时,只需要获取特定时区的当前时间。now()将时区作为输入,以提供面向时区的输出时间。但这些时区是在 皮茨 图书馆

代码#3: 使用now()来处理特定的时区。

# Python3 code to demonstrate
# attributes of now() for timezone
# for now()
import datetime
# for timezone()
import pytz
# using now() to get current time
current_time = datetime.datetime.now(pytz.timezone( 'Asia / Calcutta' ))
# printing current time in india
print ( "The current time in india is : " )
print (current_time)


输出:

The current time in india is : 
2018-03-29 03:09:33.878000+05:30

注: 以上代码在在线IDE上无法运行,因为缺少 皮茨 单元 申请: 在开发任何真实世界的应用程序时,我们可能需要显示任何时区的实时信息。函数可以非常高效和容易地完成这里的工作。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享