问题:如何在Python中获取当前时间

获取当前时间的模块/方法是什么?

What is the module/method used to get the current time?


回答 0

采用:

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

而只是时间:

>>> datetime.datetime.now().time()
datetime.time(15, 8, 24, 78915)

>>> print(datetime.datetime.now().time())
15:08:24.789150

请参阅文档以获取更多信息。

要保存输入,可以datetimedatetime模块中导入对象:

>>> from datetime import datetime

然后datetime.从以上所有位置移除引线。

Use:

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

And just the time:

>>> datetime.datetime.now().time()
datetime.time(15, 8, 24, 78915)

>>> print(datetime.datetime.now().time())
15:08:24.789150

See the documentation for more information.

To save typing, you can import the datetime object from the datetime module:

>>> from datetime import datetime

Then remove the leading datetime. from all of the above.


回答 1

您可以使用time.strftime()

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

You can use time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

回答 2

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

对于此示例,输出将如下所示: '2013-09-18 11:16:32'

这是strftime指令列表。

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

For this example, the output will be like this: '2013-09-18 11:16:32'

Here is the list of strftime directives.


回答 3

Harley的答案相似,但使用该str()函数可得到快速n脏的,人类可读的格式:

>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'

Similar to Harley’s answer, but use the str() function for a quick-n-dirty, slightly more human readable format:

>>> from datetime import datetime
>>> str(datetime.now())
'2011-05-03 17:45:35.177000'

回答 4

如何使用Python获取当前时间?

time模块

time模块提供的功能可以告诉我们时间(自纪元以来的秒数)以及其他实用程序。

import time

Unix时代时间

这是保存数据库时应使用的时间戳格式。它是一个简单的浮点数,可以转换为整数。这对于以秒为单位的算术也很有用,因为它代表自1970年1月1日00:00:00以来的秒数,并且相对于我们接下来要看的其他时间表示,它是记忆光。

>>> time.time()
1424233311.771502

该时间戳记不占leap秒,因此不是线性的-leap秒将被忽略。因此,尽管它不等同于国际UTC标准,但它很接近,因此对于大多数记录保存情况而言,这是相当好的。

但是,这对于人工调度而言并不理想。如果您希望在某个特定时间发生将来的事件,则需要使用可以解析为datetime对象或序列化datetime对象的字符串存储该时间(稍后将对此进行描述)。

time.ctime

您还可以用操作系统首选的方式来表示当前时间(这意味着当您更改系统首选项时,它可以更改,因此请不要像其他人所期望的那样,将其作为所有系统的标准时间) 。这通常是用户友好的,但通常不会导致字符串可以按时间顺序排序:

>>> time.ctime()
'Tue Feb 17 23:21:56 2015'

您还可以通过以下方式将时间戳混合为易于阅读的形式ctime

>>> time.ctime(1424233311.771502)
'Tue Feb 17 23:21:51 2015'

这种转换也不利于保存记录(除非只能由人类解析的文本,并且随着光学字符识别和人工智能的改进,我认为这些案件的数量将会减少)。

datetime 模组

datetime模块在这里也非常有用:

>>> import datetime

datetime.datetime.now

datetime.now是一类方法,它返回当前时间。它使用time.localtime不带时区信息的(如果未提供,否则请参阅下面的了解时区)。它具有在外壳上回显的表示形式(允许您重新创建等效的对象),但是在打印(或强制转换为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

日期时间 utcnow

通过执行以下操作,您可以获取全球标准UTC时间中的datetime对象:

>>> datetime.datetime.utcnow()
datetime.datetime(2015, 2, 18, 4, 53, 28, 394163)
>>> print(datetime.datetime.utcnow())
2015-02-18 04:53:31.783988

UTC是几乎等同于GMT时区的时间标准。(虽然GMT和UTC的夏令时不变,但他们的用户可能会在夏季切换到其他时区,例如英国夏令时。)

datetime时区感知

但是,到目前为止,我们创建的datetime对象都无法轻松转换为各种时区。我们可以使用以下pytz模块解决该问题:

>>> import pytz
>>> then = datetime.datetime.now(pytz.utc)
>>> then
datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>)

等效地,在Python 3中,我们有一个timezone带有utc timezone实例的类,它也使对象知道时区(但在没有方便的pytz模块的情况下,转换成另一个时区留给读者练习):

>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc)

而且我们看到我们可以轻松地从原始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

您还可以使用pytztimezone localize方法或通过替换tzinfo属性(使用replace,这是盲目的完成)来使朴素的datetime对象知道的,但是这些方法比最佳实践更多的是不得已而为之:

>>> 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>)

pytz模块使我们能够使datetime对象知道时区,并将时间转换为pytz模块中可用的数百个时区。

人们可以表面上连载这个对象UTC时间和存储在数据库中,但它需要远远更多的内存和比简单地存储Unix纪元的时间,这是我第一次表现出更容易出错。

其他查看时间的方式更容易出错,尤其是在处理可能来自不同时区的数据时。您希望不要将字符串或序列化日期时间对象用于哪个时区。

如果您正在使用Python为用户显示时间,则ctime可以很好地工作,而不是在表中(通常排序不佳),而是在时钟中。但是,我个人建议在Python中使用Unix时间或时区感知UTC datetime对象处理时间时。

How do I get the current time in Python?

The time module

The time module provides functions that tells us the time in “seconds since the epoch” as well as other utilities.

import time

Unix Epoch Time

This is the format you should get timestamps in for saving in databases. It is a simple floating point number that can be converted to an integer. It is also good for arithmetic in seconds, as it represents the number of seconds since Jan 1, 1970 00:00:00, and it is memory light relative to the other representations of time we’ll be looking at next:

>>> time.time()
1424233311.771502

This timestamp does not account for leap-seconds, so it’s not linear – leap seconds are ignored. So while it is not equivalent to the international UTC standard, it is close, and therefore quite good for most cases of record-keeping.

This is not ideal for human scheduling, however. If you have a future event you wish to take place at a certain point in time, you’ll want to store that time with a string that can be parsed into a datetime object or a serialized datetime object (these will be described later).

time.ctime

You can also represent the current time in the way preferred by your operating system (which means it can change when you change your system preferences, so don’t rely on this to be standard across all systems, as I’ve seen others expect). This is typically user friendly, but doesn’t typically result in strings one can sort chronologically:

>>> time.ctime()
'Tue Feb 17 23:21:56 2015'

You can hydrate timestamps into human readable form with ctime as well:

>>> time.ctime(1424233311.771502)
'Tue Feb 17 23:21:51 2015'

This conversion is also not good for record-keeping (except in text that will only be parsed by humans – and with improved Optical Character Recognition and Artificial Intelligence, I think the number of these cases will diminish).

datetime module

The datetime module is also quite useful here:

>>> import datetime

datetime.datetime.now

The datetime.now is a class method that returns the current time. It uses the time.localtime without the timezone info (if not given, otherwise see timezone aware below). It has a representation (which would allow you to recreate an equivalent object) echoed on the shell, but when printed (or coerced to a str), it is in human readable (and nearly ISO) format, and the lexicographic sort is equivalent to the chronological sort:

>>> datetime.datetime.now()
datetime.datetime(2015, 2, 17, 23, 43, 49, 94252)
>>> print(datetime.datetime.now())
2015-02-17 23:43:51.782461

datetime’s utcnow

You can get a datetime object in UTC time, a global standard, by doing this:

>>> datetime.datetime.utcnow()
datetime.datetime(2015, 2, 18, 4, 53, 28, 394163)
>>> print(datetime.datetime.utcnow())
2015-02-18 04:53:31.783988

UTC is a time standard that is nearly equivalent to the GMT timezone. (While GMT and UTC do not change for Daylight Savings Time, their users may switch to other timezones, like British Summer Time, during the Summer.)

datetime timezone aware

However, none of the datetime objects we’ve created so far can be easily converted to various timezones. We can solve that problem with the pytz module:

>>> import pytz
>>> then = datetime.datetime.now(pytz.utc)
>>> then
datetime.datetime(2015, 2, 18, 4, 55, 58, 753949, tzinfo=<UTC>)

Equivalently, in Python 3 we have the timezone class with a utc timezone instance attached, which also makes the object timezone aware (but to convert to another timezone without the handy pytz module is left as an exercise to the reader):

>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc)

And we see we can easily convert to timezones from the original utc object.

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

You can also make a naive datetime object aware with the pytz timezone localize method, or by replacing the tzinfo attribute (with replace, this is done blindly), but these are more last resorts than best practices:

>>> 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>)

The pytz module allows us to make our datetime objects timezone aware and convert the times to the hundreds of timezones available in the pytz module.

One could ostensibly serialize this object for UTC time and store that in a database, but it would require far more memory and be more prone to error than simply storing the Unix Epoch time, which I demonstrated first.

The other ways of viewing times are much more error prone, especially when dealing with data that may come from different time zones. You want there to be no confusion as to which timezone a string or serialized datetime object was intended for.

If you’re displaying the time with Python for the user, ctime works nicely, not in a table (it doesn’t typically sort well), but perhaps in a clock. However, I personally recommend, when dealing with time in Python, either using Unix time, or a timezone aware UTC datetime object.


回答 5

from time import time

t = time()
  • t -浮点数,适用于时间间隔测量。

Unix和Windows平台有所不同。

Do

from time import time

t = time()
  • t – float number, good for time interval measurement.

There is some difference for Unix and Windows platforms.


回答 6

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'

以指定格式输出当前GMT。还有一种localtime()方法。

页面有更多详细信息。

>>> from time import gmtime, strftime
>>> strftime("%a, %d %b %Y %X +0000", gmtime())
'Tue, 06 Jan 2009 04:54:56 +0000'

That outputs the current GMT in the specified format. There is also a localtime() method.

This page has more details.


回答 7

先前的答案都是不错的建议,但我发现它最容易使用ctime()

In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'

这样可以很好地格式化当前本地时间的字符串表示形式。

The previous answers are all good suggestions, but I find it easiest to use ctime():

In [2]: from time import ctime
In [3]: ctime()
Out[3]: 'Thu Oct 31 11:40:53 2013'

This gives a nicely formatted string representation of the current local time.


回答 8

最快的方法是:

>>> import time
>>> time.strftime("%Y%m%d")
'20130924'

The quickest way is:

>>> import time
>>> time.strftime("%Y%m%d")
'20130924'

回答 9

如果您需要当前时间作为time对象:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)

If you need current time as a time object:

>>> import datetime
>>> now = datetime.datetime.now()
>>> datetime.time(now.hour, now.minute, now.second)
datetime.time(11, 23, 44)

回答 10

.isoformat() 在文档中,但尚未在此处(这与@Ray Vega的答案非常相似):

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'

.isoformat() is in the documentation, but not yet here (this is mighty similar to @Ray Vega’s answer):

>>> import datetime
>>> datetime.datetime.now().isoformat()
'2013-06-24T20:35:55.982000'

回答 11

为什么不问美国海军的官方计时器美国海军天文台呢?

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])

如果您像我一样住在华盛顿特区,那么延迟可能不会太糟糕…

Why not ask the U.S. Naval Observatory, the official timekeeper of the United States Navy?

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])

If you live in the D.C. area (like me) the latency might not be too bad…


回答 12

使用熊猫来获取当前时间,有点过头了:

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)

输出:

2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693

Using pandas to get the current time, kind of overkilling the problem at hand:

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)

Output:

2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693

回答 13

这就是我最终要进行的工作:

>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11

此外,该表是选择适当的格式代码得到格式化只是你想要的方式日期(从Python的“日期时间”的文档的必要参考这里)。

strftime格式代码表

This is what I ended up going with:

>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11

Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python “datetime” documentation here).

strftime format code table


回答 14

如果您已经在使用numpy,则可以直接使用numpy.datetime64()函数。

import numpy as np
str(np.datetime64('now'))

仅限日期:

str(np.datetime64('today'))

或者,如果您已经在使用熊猫,则可以使用pandas.to_datetime()函数

import pandas as pd
str(pd.to_datetime('now'))

要么,

str(pd.to_datetime('today'))

if you are using numpy already then directly you can use numpy.datetime64() function.

import numpy as np
str(np.datetime64('now'))

for only date:

str(np.datetime64('today'))

or, if you are using pandas already then you can use pandas.to_datetime() function

import pandas as pd
str(pd.to_datetime('now'))

or,

str(pd.to_datetime('today'))

回答 15

您可以使用以下time模块:

import time
print time.strftime("%d/%m/%Y")

>>> 06/02/2015

资本的使用Y给出了全年,而使用则y给出了06/02/15

您还可以使用以下代码来延长时间:

time.strftime("%a, %d %b %Y %H:%M:%S")
>>> 'Fri, 06 Feb 2015 17:45:09'

You can use the time module:

import time
print time.strftime("%d/%m/%Y")

>>> 06/02/2015

The use of the capital Y gives the full year, and using y would give 06/02/15.

You could also use the following code to give a more lengthy time:

time.strftime("%a, %d %b %Y %H:%M:%S")
>>> 'Fri, 06 Feb 2015 17:45:09'

回答 16

datetime.now()返回当前时间作为朴素的datetime对象,该对象表示本地时区中的时间。该值可能不明确,例如在DST转换期间(“回退”)。为避免歧义,应使用UTC时区:

from datetime import datetime

utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417

或具有附加时区信息的时区感知对象(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

datetime.now() returns the current time as a naive datetime object that represents time in the local timezone. That value may be ambiguous e.g., during DST transitions (“fall back”). To avoid ambiguity either UTC timezone should be used:

from datetime import datetime

utc_time = datetime.utcnow()
print(utc_time) # -> 2014-12-22 22:48:59.916417

Or a timezone-aware object that has the corresponding timezone info attached (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

回答 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

dir(date)或任何变量,包括包装。您可以获得与该变量关联的所有属性和方法。

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

Do dir(date) or any variables including the package. You can get all the attributes and methods associated with the variable.


回答 18

>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'
>>> import datetime, time
>>> time = time.strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:21:38:20S'

回答 19

默认情况下,now()函数以YYYY-MM-DD HH:MM:SS:MS格式返回输出。使用以下示例脚本在Python脚本中获取当前日期和时间,并在屏幕上打印结果。创建getDateTime1.py具有以下内容的文件。

import datetime

currentDT = datetime.datetime.now()
print (str(currentDT))

输出如下所示:

2018-03-01 17:03:46.759624

By default, now() function returns output in the YYYY-MM-DD HH:MM:SS:MS format. Use the below sample script to get the current date and time in a Python script and print results on the screen. Create file getDateTime1.py with the below content.

import datetime

currentDT = datetime.datetime.now()
print (str(currentDT))

The output looks like below:

2018-03-01 17:03:46.759624

回答 20

这个问题并不需要仅仅为了它而提供一个新的答案……但是,一个闪亮的新玩具/模块就足够了。那就是Pendulum库,它似乎可以完成arrow尝试的各种工作,但没有固有的缺陷和bug困扰着arrow。

例如,原始问题的答案:

>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00

有很多需要解决的标准,包括多个RFC和ISO。曾经把它们混在一起;不用担心,请看一看dir(pendulum.constants)。不过,这里还有RFC和ISO格式。

当我们说本地的时候,虽然是什么意思?好吧,我的意思是:

>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>

大概大多数人都在别的地方。

继续下去。长话短说:Pendulum尝试在日期和时间上执行HTTP请求的操作。值得考虑,尤其是它的易用性和广泛的文档资料。

This question doesn’t need a new answer just for the sake of it … a shiny new-ish toy/module, however, is enough justification. That being the Pendulum library, which appears to do the sort of things which arrow attempted, except without the inherent flaws and bugs which beset arrow.

For instance, the answer to the original question:

>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00

There’s a lot of standards which need addressing, including multiple RFCs and ISOs, to worry about. Ever get them mixed up; not to worry, take a little look into dir(pendulum.constants) There’s a bit more than RFC and ISO formats there, though.

When we say local, though what do we mean? Well I mean:

>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>

Presumably most of the rest of you mean somewhere else.

And on it goes. Long story short: Pendulum attempts to do for date and time what requests did for HTTP. It’s worth consideration, particularly for both its ease of use and extensive documentation.


回答 21

时区的当前时间

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

Current time of a timezone

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

回答 22

试用http://crsmithdev.com/arrow/中的箭头模块:

import arrow
arrow.now()

或UTC版本:

arrow.utcnow()

要更改其输出,请添加.format():

arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')

对于特定时区:

arrow.now('US/Pacific')

一小时前:

arrow.utcnow().replace(hours=-1)

或者,如果您要要旨。

arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'

Try the arrow module from http://crsmithdev.com/arrow/:

import arrow
arrow.now()

Or the UTC version:

arrow.utcnow()

To change its output, add .format():

arrow.utcnow().format('YYYY-MM-DD HH:mm:ss ZZ')

For a specific timezone:

arrow.now('US/Pacific')

An hour ago:

arrow.utcnow().replace(hours=-1)

Or if you want the gist.

arrow.get('2013-05-11T21:23:58.970460+00:00').humanize()
>>> '2 years ago'

回答 23

我想用毫秒来获取时间。一种简单的获取方法:

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

但是我只想毫秒,对不对?获得它们的最短方法:

import time

time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751

从上一个乘法中添加或删除零以调整小数点位数,或者仅:

def get_time_str(decimal_points=3):
    return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

I want to get the time with milliseconds. A simple way to get them:

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

But I want only milliseconds, right? The shortest way to get them:

import time

time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751

Add or remove zeroes from the last multiplication to adjust number of decimal points, or just:

def get_time_str(decimal_points=3):
    return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

回答 24

您可以使用此功能获取时间(不幸的是,它没有显示AM或PM):

def gettime():
    from datetime import datetime
    return ((str(datetime.now())).split(' ')[1]).split('.')[0]

要获取以后合并的小时,分​​钟,秒和毫秒,可以使用以下功能:

小时:

def gethour():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]

分钟:

def getminute():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]

第二:

def getsecond():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]

毫秒:

def getmillisecond():
    from datetime import datetime
    return (str(datetime.now())).split('.')[1]

You can use this function to get the time (unfortunately it doesn’t say AM or PM):

def gettime():
    from datetime import datetime
    return ((str(datetime.now())).split(' ')[1]).split('.')[0]

To get the hours, minutes, seconds and milliseconds to merge later, you can use these functions:

Hour:

def gethour():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[0]

Minute:

def getminute():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[1]

Second:

def getsecond():
    from datetime import datetime
    return (((str(datetime.now())).split(' ')[1]).split('.')[0]).split(':')[2]

Millisecond:

def getmillisecond():
    from datetime import datetime
    return (str(datetime.now())).split('.')[1]

回答 25

如果只需要当前时间戳(以毫秒为单位)(例如,测量执行时间),则也可以使用“ 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))

If you just want the current timestamp in ms (for example, to measure execution time), you can also use the “timeit” module:

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))

回答 26

以下是我用来获取时间而不必进行格式化的内容。有些人不喜欢split方法,但是在这里很有用:

from time import ctime
print ctime().split()[3]

它将以HH:MM:SS格式打印。

The following is what I use to get the time without having to format. Some people don’t like the split method, but it is useful here:

from time import ctime
print ctime().split()[3]

It will print in HH:MM:SS format.


回答 27

因为还没有人提及它,所以我最近遇到了这个问题……pytz时区的fromutc()方法与datetime的utcnow()结合是我发现获得有用的当前时间(和日期)的最佳方法在任何时区。

from datetime import datetime

import pytz


JST = pytz.timezone("Asia/Tokyo")


local_time = JST.fromutc(datetime.utcnow())

如果您想要的只是时间,那么您可以使用local_time.time()

Because no one has mentioned it yet, and this is something I ran into recently… a pytz timezone’s fromutc() method combined with datetime’s utcnow() is the best way I’ve found to get a useful current time (and date) in any timezone.

from datetime import datetime

import pytz


JST = pytz.timezone("Asia/Tokyo")


local_time = JST.fromutc(datetime.utcnow())

If all you want is the time, you can then get that with local_time.time().


回答 28

这个问题是针对Python的,但是由于Django是Python使用最广泛的框架之一,因此必须注意,如果您使用的是Django,则可以始终使用timezone.now()而不是datetime.datetime.now()。前者是时区“知道”的,而后者则不是。

请参阅此SO答案Django文档,以获取详细信息和背后的原理timezone.now()

from django.utils import timezone

now = timezone.now()

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()

回答 29

您可以使用ctime()来做到这一点:

from time import time, ctime
t = time()
ctime(t)

输出:

Sat Sep 14 21:27:08 2019

这些输出是不同的,因为返回的时间戳ctime()取决于您的地理位置。

You can do so using ctime():

from time import time, ctime
t = time()
ctime(t)

output:

Sat Sep 14 21:27:08 2019

These outputs are different because the timestamp returned by ctime() depends on your geographical location.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。