Ver*_*hon 758 python datetime strftime unix-timestamp
我在Python中有一个表示unix时间戳(即"1284101485")的字符串,我想将其转换为可读日期.当我使用时time.strftime,我得到一个TypeError:
>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
Run Code Online (Sandbox Code Playgroud)
Mic*_*las 1125
使用datetime模块:
from datetime import datetime
ts = int("1284101485")
# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
Run Code Online (Sandbox Code Playgroud)
Dan*_*iel 224
>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)
Run Code Online (Sandbox Code Playgroud)
取自http://seehuhn.de/pages/pdate
rka*_*ach 143
投票最多的答案建议使用fromtimestamp,因为它使用本地时区,因此很容易出错.为了避免问题,更好的方法是使用UTC:
datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')
Run Code Online (Sandbox Code Playgroud)
posix_time是您要转换的Posix纪元时间
Joh*_*ooy 71
>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'
Run Code Online (Sandbox Code Playgroud)
jfs*_*jfs 59
有两个部分:
即使本地时区过去具有不同的utc偏移并且python无法访问tz数据库,也可以通过便携式获取本地时间的方法是使用pytz时区:
#!/usr/bin/env python
from datetime import datetime
import tzlocal # $ pip install tzlocal
unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)
Run Code Online (Sandbox Code Playgroud)
要显示它,您可以使用系统支持的任何时间格式,例如:
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y")) # print date in your format
Run Code Online (Sandbox Code Playgroud)
如果您不需要当地时间,则可以获得可读的UTC时间:
utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))
Run Code Online (Sandbox Code Playgroud)
如果您不关心可能影响返回日期的时区问题,或者python是否可以访问系统上的tz数据库:
local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))
Run Code Online (Sandbox Code Playgroud)
在Python 3上,您可以仅使用stdlib获取时区感知日期时间(如果python无法访问系统上的tz数据库,例如在Windows上,则UTC偏移可能是错误的):
#!/usr/bin/env python3
from datetime import datetime, timezone
utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
Run Code Online (Sandbox Code Playgroud)
time模块中的函数是相应C API周围的瘦包装器,因此它们可能比相应的datetime方法更不便携,否则您也可以使用它们:
#!/usr/bin/env python
import time
unix_timestamp = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time))
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))
Run Code Online (Sandbox Code Playgroud)
Con*_*ngo 57
在 Python 3.6+ 中:
import datetime
timestamp = 1579117901
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")
Run Code Online (Sandbox Code Playgroud)
2020-01-15 19:51:41
Run Code Online (Sandbox Code Playgroud)
type(value)要将日期保存为字符串然后打印它,请使用以下命令:
my_date = f"{value:%Y-%m-%d %H:%M:%S}"
print(my_date)
Run Code Online (Sandbox Code Playgroud)
Jar*_*ows 34
对于来自UNIX时间戳的人类可读时间戳,我之前在脚本中使用过它:
import os, datetime
datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")
Run Code Online (Sandbox Code Playgroud)
输出:
'2012年12月26日'
Nic*_*ick 24
你可以像这样转换当前时间
t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'
Run Code Online (Sandbox Code Playgroud)
将字符串中的日期转换为不同的格式.
import datetime,time
def createDateObject(str_date,strFormat="%Y-%m-%d"):
timeStamp = time.mktime(time.strptime(str_date,strFormat))
return datetime.datetime.fromtimestamp(timeStamp)
def FormatDate(objectDate,strFormat="%Y-%m-%d"):
return objectDate.strftime(strFormat)
Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')
Output 03-03-2013
Run Code Online (Sandbox Code Playgroud)
小智 22
除了使用time/datetime包之外,pandas还可以用来解决同样的问题.这就是我们如何使用pandas将时间戳转换为可读日期:
时间戳可以采用两种格式:
13位(毫秒) - 要将毫秒转换为日期,请使用:
import pandas
result_ms=pandas.to_datetime('1493530261000',unit='ms')
str(result_ms)
Output: '2017-04-30 05:31:01'
Run Code Online (Sandbox Code Playgroud)10位数(秒) - 要将秒转换为日期,请使用:
import pandas
result_s=pandas.to_datetime('1493530261',unit='s')
str(result_s)
Output: '2017-04-30 05:31:01'
Run Code Online (Sandbox Code Playgroud)Ris*_*ani 18
timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)
从时间戳开始随时间获取可读日期,您也可以更改日期格式.
请注意,这utcfromtimestamp可能会导致意外结果,因为它返回一个简单的 datetime 对象。Python 将原始日期时间视为本地时间- 而 UNIX 时间是指 UTC。
可以通过在 中设置tz参数来避免这种歧义fromtimestamp:
from datetime import datetime, timezone
dtobj = datetime.fromtimestamp(1284101485, timezone.utc)
>>> print(repr(dtobj))
datetime.datetime(2010, 9, 10, 6, 51, 25, tzinfo=datetime.timezone.utc)
Run Code Online (Sandbox Code Playgroud)
现在您可以格式化为字符串,例如符合 ISO8601 的格式:
>>> print(dtobj.isoformat(timespec='milliseconds').replace('+00:00', 'Z'))
2010-09-10T06:51:25.000Z
Run Code Online (Sandbox Code Playgroud)
from datetime import datetime
unixtime = int('1284101485')
# Print with local time
print(datetime.fromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
# Print with UTC time
print(datetime.utcfromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
Run Code Online (Sandbox Code Playgroud)
datetime.fromtimestamp(timestamp):返回POSIX时间戳对应的本地日期,如time.time().
datetime.utcfromtimestamp(timestamp):返回POSIX时间戳对应的UTC日期时间,tzinfo为None。(生成的对象很幼稚。)
小智 7
使用以下代码,希望它能解决您的问题。
import datetime as dt
print(dt.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))
Run Code Online (Sandbox Code Playgroud)
import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
Run Code Online (Sandbox Code Playgroud)
小智 6
可以使用gmtime和format函数完成此操作的另一种方法;
from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))
Run Code Online (Sandbox Code Playgroud)
输出: 2018-10-4 11:57:44
| 归档时间: |
|
| 查看次数: |
965565 次 |
| 最近记录: |