700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 将Unix时间戳字符串转换为可读日期

将Unix时间戳字符串转换为可读日期

时间:2021-12-28 15:25:15

相关推荐

将Unix时间戳字符串转换为可读日期

我有一个表示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

#1楼

对于来自UNIX时间戳的可读时间戳,我以前在脚本中使用过此时间戳:

import os, datetimedatetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")

输出:

'12月26日'

#2楼

快速又脏的一个衬里:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

'-5-5-1-9-43'

#3楼

import datetimetemp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')print temp

#4楼

我刚刚成功使用过:

>>> type(tstamp)pandas.tslib.Timestamp>>> newDt = tstamp.date()>>> type(newDt)datetime.date

#5楼

您可以使用easy_date使其变得容易:

import date_convertermy_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")

#6楼

>>> from datetime import datetime>>> datetime.fromtimestamp(1172969203.1)datetime.datetime(, 3, 4, 0, 46, 43, 100000)

取自http://seehuhn.de/pages/pdate

#7楼

使用datetime模块:

from datetime import datetimets = int("1284101485")# if you encounter a "year is out of range" error the timestamp# may be in milliseconds, try `ts /= 1000` in that caseprint(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

#8楼

>>> import time>>> time.ctime(int("1284101485"))'Fri Sep 10 16:51:25 '>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))'09/10/10 16:51'

#9楼

投票最多的答案建议使用fromtimestamp,因为它使用本地时区,因此容易出错。 为了避免出现问题,更好的方法是使用UTC:

datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')

其中posix_time是要转换的Posix纪元时间

#10楼

有两个部分:

将Unix时间戳(“自纪元以来的秒数”)转换为本地时间 以所需格式显示当地时间。

即使本地时区过去有不同的utc偏移并且python无法访问tz数据库,一种获取有效本地时间的方法是使用pytz时区:

#!/usr/bin/env pythonfrom datetime import datetimeimport tzlocal # $ pip install tzlocalunix_timestamp = float("1284101485")local_timezone = tzlocal.get_localzone() # get pytz timezonelocal_time = datetime.fromtimestamp(unix_timestamp, local_timezone)

要显示它,您可以使用系统支持的任何时间格式,例如:

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

如果您不需要当地时间,请改为获取可读的UTC时间:

utc_time = datetime.utcfromtimestamp(unix_timestamp)print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))

如果您不关心可能会影响返回日期的时区问题,或者python是否有权访问系统上的tz数据库:

local_time = datetime.fromtimestamp(unix_timestamp)print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))

在Python 3上,您可以仅使用stdlib获得时区感知日期时间(如果python无法访问系统上的tz数据库,例如Windows上的UTC偏移量可能是错误的):

#!/usr/bin/env python3from datetime import datetime, timezoneutc_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)"))

time模块中的函数是对应C API的薄包装,因此它们可能不如对应的datetime方法可移植性强,否则您也可以使用它们:

#!/usr/bin/env pythonimport timeunix_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))

#11楼

除了使用time / datetime包之外,pandas还可以用于解决相同的问题。这是我们可以使用pandas时间戳转换为可读日期的方法

时间戳可以有两种格式:

13位数字(毫秒)-要将毫秒转换日期,请使用:

import pandas result_ms=pandas.to_datetime('1493530261000',unit='ms') str(result_ms) Output: '-04-30 05:31:01'

10位(秒)-要将转换为日期,请使用:

import pandas result_s=pandas.to_datetime('1493530261',unit='s') str(result_s) Output: '-04-30 05:31:01'

#12楼

timestamp ="124542124"value = datetime.datetime.fromtimestamp(timestamp)exct_time = value.strftime('%d %B %Y %H:%M:%S')

您还可以从时间戳获取带有时间的可读日期,也可以更改日期格式。

#13楼

可以使用gmtime和format函数完成此操作的另一种方法;

from time import gmtimeprint('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))

输出:-10-4 11:57:44

#14楼

您可以像这样转换当前时间

t=datetime.fromtimestamp(time.time())t.strftime('%Y-%m-%d')'-03-07'

将字符串中的日期转换为其他格式。

import datetime,timedef 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('-03-03')print FormatDate(o,'%d-%m-%Y')Output 03-03-

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。