python end用法_Python now()用法及代码示例

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

语法:datetime.now(tz)

参数:

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()以时区为输入,以时区为导向的输出时间。但是这些时区是在pytz库中定义的。

代码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

注意:由于缺少pytz模块,以上代码无法在在线IDE上运行。应用程序:开发任何实际应用程序时,我们可能需要显示任何时区的实时时间。 now()函数可以非常高效且轻松地完成此处的工作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值