How to get the current time in Python

2018-12-31 23:16发布

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

30条回答
呛了眼睛熬了心
2楼-- · 2018-12-31 23:28

If you are using NumPy already then directly you can use the numpy.datetime64() function.

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

For only the date:

str(np.datetime64('today'))

Or, if you are using Pandas already then you can use the pandas.to_datetime() function:

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

Or:

str(pd.to_datetime('today'))
查看更多
墨雨无痕
3楼-- · 2018-12-31 23:30

Using Pandas to get the current time, kind of over killing 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
查看更多
孤独总比滥情好
4楼-- · 2018-12-31 23:31

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)
查看更多
永恒的永恒
5楼-- · 2018-12-31 23:32

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

查看更多
泛滥B
6楼-- · 2018-12-31 23:34
>>> import datetime, time
>>> time = strftime("%H:%M:%S:%MS", time.localtime())
>>> print time
'00:20:58:20S'
查看更多
临风纵饮
7楼-- · 2018-12-31 23:34

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'
查看更多
登录 后发表回答