Har*_*mbe 2787
使用:
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(datetime.datetime.now())
2009-01-06 15:08:24.789150
Run Code Online (Sandbox Code Playgroud)
只是时间:
>>> datetime.datetime.now().time()
datetime.time(15, 8, 24, 78915)
>>> print(datetime.datetime.now().time())
15:08:24.789150
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅文档.
要保存键入,可以datetime
从datetime
模块导入对象:
>>> from datetime import datetime
Run Code Online (Sandbox Code Playgroud)
然后datetime.
从上述所有内容中删除前导.
Sea*_*mes 903
你可以使用time.strftime()
:
>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'
Run Code Online (Sandbox Code Playgroud)
Par*_*erz 543
from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)
对于此示例,输出将如下所示: '2013-09-18 11:16:32'
这是strftime的列表.
Ray*_*ega 440
与Harley的答案类似,但使用该str()
功能可以实现快速,简洁,易读的格式:
>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'
Run Code Online (Sandbox Code Playgroud)
Aar*_*all 329
如何在Python中获取当前时间?
time
模块该time
模块提供的功能告诉我们"自纪元以来的秒数"以及其他实用程序的时间.
import time
Run Code Online (Sandbox Code Playgroud)
这是您应该获取用于保存数据库的时间戳的格式.它是一个简单的浮点数,可以转换为整数.它也适用于以秒为单位的算术运算,因为它表示自1970年1月1日00:00:00以来的秒数,并且它是相对于我们接下来要查看的其他时间表示的记忆灯:
>>> time.time()
1424233311.771502
Run Code Online (Sandbox Code Playgroud)
此时间戳不考虑闰秒,因此它不是线性的 - 忽略闰秒.因此虽然它不等同于国际UTC标准,但它很接近,因此对于大多数记录保存案例来说非常好.
然而,这对于人类调度来说并不理想.如果您希望在某个特定时间点发生未来事件,则需要将该时间存储为可以解析为日期时间对象或序列化日期时间对象的字符串(这些将在后面描述).
time.ctime
您还可以按照操作系统首选的方式表示当前时间(这意味着它可以在您更改系统首选项时更改,因此不要依赖于此在所有系统中都是标准的,正如我见过其他人所期望的那样) .这通常是用户友好的,但通常不会导致字符串按时间顺序排序:
>>> time.ctime()
'Tue Feb 17 23:21:56 2015'
Run Code Online (Sandbox Code Playgroud)
您还可以将时间戳水合成人类可读的形式ctime
:
>>> time.ctime(1424233311.771502)
'Tue Feb 17 23:21:51 2015'
Run Code Online (Sandbox Code Playgroud)
这种转换也不利于记录保存(除了只能由人类解析的文本 - 并且通过改进的光学字符识别和人工智能,我认为这些情况的数量将减少).
datetime
模该datetime
模块在这里也很有用:
>>> import datetime
Run Code Online (Sandbox Code Playgroud)
datetime.datetime.now
这datetime.now
是一个返回当前时间的类方法.它使用time.localtime
没有时区信息(如果没有给出,否则请参见下面的时区).它有一个表示(允许你重新创建一个等效对象)在shell上回显,但是当打印(或强制转换为a str
)时,它是人类可读(和接近ISO)格式,并且词典排序等同于按时间顺序排序:
>>> datetime.datetime.now()
datetime.datetime(2015, 2, 17, 23, 43, 49, 94252)
>>> print(datetime.datetime.now())
2015-02-17 23:43:51.782461
Run Code Online (Sandbox Code Playgroud)
utcnow
您可以通过以下方式获取UTC时间的日期时间对象,这是一个全球标准:
>>> datetime.datetime.utcnow()
datetime.datetime(2015, 2, 18, 4, 53, 28, 394163)
>>> print(datetime.datetime.utcnow())
2015-02-18 04:53:31.783988
Run Code Online (Sandbox Code Playgroud)
UTC是一个几乎等同于GMT时区的时间标准.(虽然GMT和UTC不会因夏令时而改变,但他们的用户可能会在暑假期间切换到其他时区,例如英国夏令时.)
但是,到目前为止我们创建的日期时间对象都不能轻易转换为各种时区.我们可以用pytz
模块解决这个问题:
>>> import pytz
>>> then = datetime.datetime.now(pytz.utc)
>>> then
datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>)
Run Code Online (Sandbox Code Playgroud)
同样地,在Python 3中我们有timezone
一个timezone
附加了utc 实例的类,这也使得对象时区可以识别(但是转换到另一个时区而没有方便的pytz
模块留给读者的练习):
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc)
Run Code Online (Sandbox Code Playgroud)
我们看到我们可以轻松地从原始的utc对象转换为时区.
>>> print(then)
2015-02-18 04:55:58.753949+00:00
>>> print(then.astimezone(pytz.timezone('US/Eastern')))
2015-02-17 23:55:58.753949-05:00
Run Code Online (Sandbox Code Playgroud)
您还可以使用pytz
timezone localize
方法识别天真的日期时间对象,或者通过替换tzinfo属性(使用replace
,这是盲目地完成),但这些是最后的解决方案而不是最佳实践:
>>> pytz.utc.localize(datetime.datetime.utcnow())
datetime.datetime(2015, 2, 18, 6, 6, 29, 32285, tzinfo=<UTC>)
>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
datetime.datetime(2015, 2, 18, 6, 9, 30, 728550, tzinfo=<UTC>)
Run Code Online (Sandbox Code Playgroud)
该pytz
模块允许我们使我们的datetime
对象能够识别时区,并将时间转换为pytz
模块中可用的数百个时区.
人们可以表面上连载这个对象UTC时间和存储是在数据库中,但它需要远远更多的内存和比简单地存储Unix纪元的时间,这是我第一次表现出更容易出错.
查看时间的其他方式更容易出错,尤其是在处理可能来自不同时区的数据时.您希望不存在关于字符串或序列化日期时间对象所针对的时区的混淆.
如果您正在为用户显示Python的时间,那么ctime
可以很好地工作,而不是在表格中(通常不能很好地排序),但也许在时钟中.但是,我个人建议,在处理Python的时间时,要么使用Unix时间,要么使用时区感知的UTC datetime
对象.
max*_*axp 126
做
from time import time
t = time()
Run Code Online (Sandbox Code Playgroud)
t
- 浮点数,适用于时间间隔测量.Unix和Windows平台有一些区别.
Vij*_*Dev 94
>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'
Run Code Online (Sandbox Code Playgroud)
以指定的格式输出当前的GMT.还有一个localtime()方法.
此页面包含更多详细信息.
Eth*_*eal 62
所有好的建议,但我觉得最容易使用ctime()
自己:
In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'
Run Code Online (Sandbox Code Playgroud)
这给出了当前本地时间的格式良好的字符串表示.
nac*_*bre 48
最快的方法是
>>> import time
>>> time.strftime("%Y%m%d")
'20130924'
Run Code Online (Sandbox Code Playgroud)
blu*_*ish 45
如果您需要当前时间作为time
对象:
>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)
Run Code Online (Sandbox Code Playgroud)
emm*_*ras 33
.isoformat()
在文档中,但还没有在这里(这与@Ray Vega的答案相似):
>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'
Run Code Online (Sandbox Code Playgroud)
C8H*_*4O2 31
import requests
from lxml import html
page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])
Run Code Online (Sandbox Code Playgroud)
如果你住在DC区域(像我一样),延迟可能不会太糟糕......
小智 27
使用熊猫来获取当前时间,过度杀死手头的问题:
import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)
Run Code Online (Sandbox Code Playgroud)
输出:
2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693
Run Code Online (Sandbox Code Playgroud)
Kri*_* G. 24
这就是我最终的目的:
>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11
Run Code Online (Sandbox Code Playgroud)
此外,该表是选择适当的格式代码得到格式化只是你想要的方式日期(从Python的"日期时间"的文档的必要参考这里).
dur*_*joy 23
如果您已经使用NumPy,那么可以直接使用numpy.datetime64()函数.
import numpy as np
str(np.datetime64('now'))
Run Code Online (Sandbox Code Playgroud)
仅限日期:
str(np.datetime64('today'))
Run Code Online (Sandbox Code Playgroud)
或者,如果您已经使用Pandas,那么您可以使用pandas.to_datetime()函数:
import pandas as pd
str(pd.to_datetime('now'))
Run Code Online (Sandbox Code Playgroud)
要么:
str(pd.to_datetime('today'))
Run Code Online (Sandbox Code Playgroud)
小智 18
您可以使用该time
模块.
import time
print time.strftime("%d/%m/%Y")
>>> 06/02/2015
Run Code Online (Sandbox Code Playgroud)
资本的使用Y
给了整年,使用y
会给06/02/15
.
你也可以使用更长的时间.
time.strftime("%a, %d %b %Y %H:%M:%S")
>>> 'Fri, 06 Feb 2015 17:45:09'
Run Code Online (Sandbox Code Playgroud)
the*_*der 17
import datetime
date_time = datetime.datetime.now()
date = date_time.date() # Gives the date
time = date_time.time() # Gives the time
print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond
Run Code Online (Sandbox Code Playgroud)
做dir(date)
或包括包的任何变量.您可以获得与变量关联的所有属性和方法.
jfs*_*jfs 16
datetime.now()
将当前时间作为一个天真的日期时间对象返回,该对象表示本地时区的时间.该值可能是不明确的,例如,在DST转换期间("后退").为避免歧义,应使用UTC时区:
from datetime import datetime
utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417
Run Code Online (Sandbox Code Playgroud)
或者附加了相应时区信息的时区感知对象(Python 3.2+):
from datetime import datetime, timezone
now = datetime.now(timezone.utc).astimezone()
print(now) # -> 2014-12-23 01:49:25.837541+03:00
Run Code Online (Sandbox Code Playgroud)
cha*_*ner 16
时区的当前时间
from datetime import datetime
import pytz
tz_NY = pytz.timezone('America/New_York')
datetime_NY = datetime.now(tz_NY)
print("NY time:", datetime_NY.strftime("%H:%M:%S"))
tz_London = pytz.timezone('Europe/London')
datetime_London = datetime.now(tz_London)
print("London time:", datetime_London.strftime("%H:%M:%S"))
tz_India = pytz.timezone('Asia/India')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))
#list timezones
pytz.all_timezones
Run Code Online (Sandbox Code Playgroud)
Umu*_*Gad 14
您可以尝试以下操作
import datetime
now = datetime.datetime.now()
print(now)
Run Code Online (Sandbox Code Playgroud)
或者
import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%b-%d, %A %I:%M:%S"))
Run Code Online (Sandbox Code Playgroud)
use*_*113 13
>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'
Run Code Online (Sandbox Code Playgroud)
小智 13
默认情况下,now()
函数以YYYY-MM-DD HH:MM:SS:MS
格式返回输出.使用以下示例脚本在Python脚本中获取当前日期和时间,并在屏幕上打印结果.getDateTime1.py
使用以下内容创建文件.
import datetime
currentDT = datetime.datetime.now()
print (str(currentDT))
Run Code Online (Sandbox Code Playgroud)
输出如下所示:
2018-03-01 17:03:46.759624
Run Code Online (Sandbox Code Playgroud)
Bac*_*ics 12
尝试http://crsmithdev.com/arrow/中的箭头模块:
import arrow
arrow.now()
Run Code Online (Sandbox Code Playgroud)
或者UTC版本:
arrow.utcnow()
Run Code Online (Sandbox Code Playgroud)
要更改其输出,请添加.format():
arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')
Run Code Online (Sandbox Code Playgroud)
对于特定时区:
arrow.now('US/Pacific')
Run Code Online (Sandbox Code Playgroud)
一小时前:
arrow.utcnow().replace(hours=-1)
Run Code Online (Sandbox Code Playgroud)
或者如果你想要这个要点.
arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'
Run Code Online (Sandbox Code Playgroud)
Ben*_*Ben 12
这个问题不仅仅是为了它而需要一个新的答案......然而,一个闪亮的新玩具/模块是足够的理由.这就是Pendulum库,它似乎做了箭头尝试的那种东西,除了没有固有的缺陷和错误箭头.
例如,原始问题的答案:
>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.utcnow())
2018-08-13T19:29:35.051023+00:00
Run Code Online (Sandbox Code Playgroud)
需要担心的是许多标准需要解决,包括多个RFC和ISO.曾经混淆了他们; 不用担心,请稍微研究一下,dir(pendulum.constants)
那里有比RFC和ISO格式更多的东西.
当我们说当地时,虽然我们的意思是什么?我的意思是:
>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>
Run Code Online (Sandbox Code Playgroud)
据推测,其他大多数人都是在其他地方.
就这样吧.长话短说:Pendulum试图为日期和时间做什么请求对HTTP.值得考虑,特别是它的易用性和广泛的文档.
Job*_*mes 12
import datetime
todays_date = datetime.date.today()
print(todays_date)
>>> 2019-10-12
# adding strftime will remove the seconds
current_time = datetime.datetime.now().strftime('%H:%M')
print(current_time)
>>> 23:38
Run Code Online (Sandbox Code Playgroud)
y.s*_*hyk 11
我想用毫秒来得到时间.获得它们的简单方法:
import time, datetime
print(datetime.datetime.now().time()) # 11:20:08.272239
# Or in a more complicated way
print(datetime.datetime.now().time().isoformat()) # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239
# But do not use this:
print(time.strftime("%H:%M:%S.%f", time.localtime()), str) # 11:20:08.%f
Run Code Online (Sandbox Code Playgroud)
但我只想要几毫秒,对吗?获得它们的最短途径:
import time
time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751
Run Code Online (Sandbox Code Playgroud)
在最后一次乘法中添加或删除零以调整小数点数,或者只是:
def get_time_str(decimal_points=3):
return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)
Run Code Online (Sandbox Code Playgroud)
小智 11
您可以使用 ctime() 这样做:
from time import time, ctime
t = time()
ctime(t)
Run Code Online (Sandbox Code Playgroud)
输出:
Sat Sep 14 21:27:08 2019
这些输出是不同的,因为返回的时间戳ctime()
取决于您的地理位置。
小智 11
试试这个:-
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
Run Code Online (Sandbox Code Playgroud)
Lit*_*jan 10
方法 1:从系统日期时间获取当前日期和时间
该日期时间模块用品类处理日期和时间。
代码
from datetime import datetime,date
print("Date: "+str(date.today().year)+"-"+str(date.today().month)+"-"+str(date.today().day))
print("Year: "+str(date.today().year))
print("Month: "+str(date.today().month))
print("Day: "+str(date.today().day)+"\n")
print("Time: "+str(datetime.today().hour)+":"+str(datetime.today().minute)+":"+str(datetime.today().second))
print("Hour: "+str(datetime.today().hour))
print("Minute: "+str(datetime.today().minute))
print("Second: "+str(datetime.today().second))
print("MilliSecond: "+str(datetime.today().microsecond))
Run Code Online (Sandbox Code Playgroud)
输出会像
Date: 2020-4-18
Year: 2020
Month: 4
Day: 18
Time: 19:30:5
Hour: 19
Minute: 30
Second: 5
MilliSecond: 836071
Run Code Online (Sandbox Code Playgroud)
方法 2:如果网络可用,则获取当前日期和时间
urllib包帮助我们处理表示网页的 url。在这里,我们从网页收集数据http://just-the-time.appspot.com/并解析dateime使用包中的网页dateparser。
代码
from urllib.request import urlopen
import dateparser
time_url = urlopen(u'http://just-the-time.appspot.com/')
datetime = time_url.read().decode("utf-8", errors="ignore").split(' ')[:-1]
date = datetime[0]
time = datetime[1]
print("Date: "+str(date))
print("Year: "+str(date.split('-')[0]))
print("Month: "+str(date.split('-')[1]))
print("Day: "+str(date.split('-')[2])+'\n')
print("Time: "+str(time))
print("Hour: "+str(time.split(':')[0]))
print("Minute: "+str(time.split(':')[1]))
print("Second: "+str(time.split(':')[2]))
Run Code Online (Sandbox Code Playgroud)
输出会像
Date: 2020-04-18
Year: 2020
Month: 04
Day: 18
Time: 14:17:10
Hour: 14
Minute: 17
Second: 10
Run Code Online (Sandbox Code Playgroud)
方法 3:从机器的本地时间获取当前日期和时间
Python 的time模块提供了一个函数,用于从称为 localtime() 的纪元以来经过的秒数获取本地时间。ctime()函数以 epoch 以来经过的秒数作为参数,并返回一个表示本地时间的字符串。
代码
from time import time, ctime
datetime = ctime(time()).split(' ')
print("Date: "+str(datetime[4])+"-"+str(datetime[1])+"-"+str(datetime[2]))
print("Year: "+str(datetime[4]))
print("Month: "+str(datetime[1]))
print("Day: "+str(datetime[2]))
print("Week Day: "+str(datetime[0])+'\n')
print("Time: "+str(datetime[3]))
print("Hour: "+str(datetime[3]).split(':')[0])
print("Minute: "+str(datetime[3]).split(':')[1])
print("Second: "+str(datetime[3]).split(':')[2])
Run Code Online (Sandbox Code Playgroud)
输出会像
Date: 2020-Apr-18
Year: 2020
Month: Apr
Day: 18
Week Day: Sat
Time: 19:30:20
Hour: 19
Minute: 30
Second: 20
Run Code Online (Sandbox Code Playgroud)
如果您只想要以ms为单位的当前时间戳(例如,测量执行时间),您还可以使用"timeit"模块:
import timeit
start_time = timeit.default_timer()
do_stuff_you_want_to_measure()
end_time = timeit.default_timer()
print("Elapsed time: {}".format(end_time - start_time))
Run Code Online (Sandbox Code Playgroud)
您可以使用此功能来获取时间(不幸的是它不说AM或PM):
def gettime():
from datetime import datetime
return ((str(datetime.now())).split(' ')[1]).split('.')[0]
Run Code Online (Sandbox Code Playgroud)
要获得稍后合并的小时,分钟,秒和毫秒,您可以使用以下功能:
小时:
def gethour():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]
Run Code Online (Sandbox Code Playgroud)
分钟:
def getminute():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]
Run Code Online (Sandbox Code Playgroud)
第二:
def getsecond():
from datetime import datetime
return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]
Run Code Online (Sandbox Code Playgroud)
毫秒:
def getmillisecond():
from datetime import datetime
return (str(datetime.now())).split('.')[1]
Run Code Online (Sandbox Code Playgroud)
因为还没有人提到它,这是我最近遇到的事情......一个pytz时区的fromutc()方法结合datetime的utcnow()是我发现获得有用的当前时间(和日期)的最好方法在任何时区.
from datetime import datetime
import pytz
JST = pytz.timezone("Asia/Tokyo")
local_time = JST.fromutc(datetime.utcnow())
Run Code Online (Sandbox Code Playgroud)
如果你想要的只是时间,你就可以得到它local_time.time()
.
这太简单了。尝试:
import datetime
date_time = str(datetime.datetime.now())
date = date_time.split()[0]
time = date_time.split()[1]
Run Code Online (Sandbox Code Playgroud)
小智 7
我都列出来了,大家可以根据自己的需要来使用。
\nfrom datetime import datetime\n\nnow = datetime.now()\n\ncurrent_time = now.strftime("%H:%M:%S")\nprint("Current Time =", current_time)\n
Run Code Online (Sandbox Code Playgroud)\n\n\n输出:当前时间 = 07:41:19
\n
import time\n\nt = time.localtime()\ncurrent_time = time.strftime("%H:%M:%S", t)\nprint(current_time)\n
Run Code Online (Sandbox Code Playgroud)\n\n\n2022 年 7 月 12 日星期二 10:37:46
\n
from datetime import datetime\nimport pytz\n\n# Get the timezone object for New York\ntz_NY = pytz.timezone('America/New_York') \n\n# Get the current time in New York\ndatetime_NY = datetime.now(tz_NY)\n\n# Format the time as a string and print it\nprint("NY time:", datetime_NY.strftime("%H:%M:%S"))\n\n# Get the timezone object for London\ntz_London = pytz.timezone('Europe/London')\n\n# Get the current time in London\ndatetime_London = datetime.now(tz_London)\n\n# Format the time as a string and print it\nprint("London time:", datetime_London.strftime("%H:%M:%S"))\n
Run Code Online (Sandbox Code Playgroud)\n\n\n纽约时间:03:45:16
\n
\n\n伦敦时间:08:45:16
\n
from datetime import datetime\n\nprint("UTC Time: ", datetime.utcnow())\n
Run Code Online (Sandbox Code Playgroud)\n\n\n世界标准时间:2022-06-20 11:10:18.289111
\n
from datetime import datetime as dt\n\nx = dt.now().isoformat()\nprint('Current ISO:', x)\n
Run Code Online (Sandbox Code Playgroud)\n\n\n当前 ISO:2022-06-20T17:03:23.299672
\n
import time\n\nprint("Epoch Time is : ", int(time.time()))\n
Run Code Online (Sandbox Code Playgroud)\n\n\n大纪元时间是:1655723915
\n
import time\n\n# current GMT Time\ngmt_time = time.gmtime(time.time())\n\nprint('Current GMT Time:\\n', gmt_time)\n
Run Code Online (Sandbox Code Playgroud)\n\n\n当前 GMT 时间:\ntime.struct_time(tm_year=2022, tm_mon=6, tm_mday=20,\ntm_hour=11, tm_min=24, tm_sec=59, tm_wday=0, tm_yday=171, tm_isdst=0)
\n
time
比datetime
因为如果您不希望夏令时 (DST) 含糊不清,请使用time
.datetime
有更多可以使用的内置对象,但对时区的支持有限。以下是我用来获取时间而不必格式化的内容.有些人不喜欢split方法,但它在这里很有用:
from time import ctime
print ctime().split()[3]
Run Code Online (Sandbox Code Playgroud)
它将以HH:MM:SS格式打印.
import datetime
date_time = str(datetime.datetime.now()).split()
date,time = date_time
Run Code Online (Sandbox Code Playgroud)
日期将打印日期和时间将打印时间.
小智 6
from time import ctime
// Day {Mon,Tue,..}
print ctime().split()[0]
// Month {Jan, Feb,..}
print ctime().split()[1]
// Date {1,2,..}
print ctime().split()[2]
// HH:MM:SS
print ctime().split()[3]
// Year {2018,..}
print ctime().split()[4]
Run Code Online (Sandbox Code Playgroud)
当您调用ctime()
它时,它会将秒转换为格式的字符串'Day Month Date HH:MM:SS Year'
(例如:)'Wed January 17 16:53:22 2018'
,然后您调用的split()
方法将从您的字符串中创建一个列表['Wed','Jan','17','16:56:45','2018']
(默认分隔符是空格)。
括号用于在列表中“选择”想要的参数。
应该只调用一个代码行。人们不应该像我一样称呼它们,那只是一个例子,因为在某些情况下你会得到不同的值,罕见但并非不可能的情况。
This question is for Python but since Django is one of the most widely used frameworks for Python, its important to note that if you are using Django you can always use timezone.now()
instead of datetime.datetime.now()
. The former is timezone 'aware' while the latter is not.
See this SO answer and the Django doc for details and rationale behind timezone.now()
.
from django.utils import timezone
now = timezone.now()
Run Code Online (Sandbox Code Playgroud)
首先从datetime导入datetime模块
from datetime import datetime
Run Code Online (Sandbox Code Playgroud)
然后将当前时间打印为 'yyyy-mm-dd hh:mm:ss'
print(str(datetime.now())
Run Code Online (Sandbox Code Playgroud)
要仅获取“hh:mm:ss”形式的时间,其中 ss 代表完整的秒数加上经过的秒数的分数,只需执行以下操作:
print(str(datetime.now()[11:])
Run Code Online (Sandbox Code Playgroud)
将 datetime.now() 转换为字符串会产生一个答案,其格式类似于我们习惯的常规日期和时间。
小智 5
获取当前日期时间属性:
import datetime
currentDT = datetime.datetime.now()
print ("Current Year is: %d" % currentDT.year)
print ("Current Month is: %d" % currentDT.month)
print ("Current Day is: %d" % currentDT.day)
print ("Current Hour is: %d" % currentDT.hour)
print ("Current Minute is: %d" % currentDT.minute)
print ("Current Second is: %d" % currentDT.second)
print ("Current Microsecond is: %d" % currentDT.microsecond)
#!/usr/bin/python
import time;
ticks = time.time()
print "Number of ticks since "12:00am, Jan 1, 1970":", ticks
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3077239 次 |
最近记录: |