Skip to main content
 首页 » 编程设计

Python时间戳(13位)转字符串返回2074年以及如何将15位时间戳转换为字符串

2024年10月01日25qq78292959

所以我正在使用 Instagram API,我需要获取上传图片的时间。通常一切都很好,时间戳看起来像这样:

>>> import time 
>>> timestamp = 1497423819748 
>>> time.strftime("%d %b %Y %H:%M:%S GMT", time.gmtime(timestamp / 1000.0)).split(' ') 
['14', 'Jun', '2017', '07:03:39', 'GMT'] 

或者这个:

>>> timestamp = 1497425126 
>>> time.strftime('%d %b %Y %H:%M:%S GMT', time.gmtime(timestamp)).split(' ') 
['14', 'Jun', '2017', '07:25:26', 'GMT'] 

但是有些媒体有时间戳,看起来像这样:

>>> timestamp = 3302720163189 
>>> time.strftime("%d %b %Y %H:%M:%S GMT", time.gmtime(timestamp / 1000.0)).split(' ') 
['28', 'Aug', '2074', '22:16:03', 'GMT'] 

甚至这 15 位数字时间戳:

>>> timestamp = 186693871989665 
>>> time.strftime("%d %b %Y %H:%M:%S GMT", time.gmtime(timestamp / 100000.0)).split(' ') 
['28', 'Feb', '2029', '02:05:19', 'GMT'] 

你能帮我把这些类型的时间戳也正确地转换成字符串吗?还是这些时间戳有问题?

更新:

>>> InstagramAPI.searchLocation('High Castle') 
>>> location_id = InstagramAPI.LastJson['items'][0]['location']['pk'] 
>>> InstagramAPI.getLocationFeed(location_id) 
>>> print(InstagramAPI.LastJson['items'][9]['device_timestamp'], InstagramAPI.LastJson['items'][9]['taken_at']) 
77276011342 1497443715 

或者在 15 位数字的情况下打印:

186693871989665 1497381289

所以有时 InstagramAPI 给我的“device_timestamp”似乎有问题,我不确定,但看起来它返回的时间是用户设备拍摄的照片,而他们手机上的时间不正确)但是'taken_at'似乎返回了正确的时间戳,所以我现在就用它,但是谢谢你的帮助。如果您对此有不同的答案,我希望看到。

请您参考如下方法:

在使用 API 时,我看到了几种不同的格式

  • Unix 时间戳,10 位数字,例如1200499926
  • 带微秒的 Unix 时间戳,15 位数字,例如143062470196222
  • 带微秒的 Unix 时间戳,16 位数字,例如1278276905502403
  • Javascript 格式(不知道名字),13 位,例如1508609431327

因为我在浏览器中查看这些,所以我需要通过 Date() 解析它们,因此您的情况可能会有所不同。

无论哪种方式,唯一需要的转换是将它们中的每一个转换成一个 13 位数字的字符串,我得到了正确的输出:

// Multiply by 1000 to include milliseconds 
// > "Wed Jan 16 2008 08:12:06 GMT-0800 (Pacific Standard Time)" 
new Date(1200499926 * 1000).toString(); 
 
// Divide by 100 to scrap the extraneous microseconds 
// > "Sat May 02 2015 20:45:01 GMT-0700 (Pacific Daylight Time)" 
new Date(143062470196222 / 100).toString(); 
 
// Divide by 1000 to scrap microseconds + region 
// > "Sun Jul 04 2010 13:55:05 GMT-0700 (Pacific Daylight Time)" 
new Date(1278276905502403 / 1000).toString() 

NOTE

I'm not 100% sure why the last digit on the 15-digit timestamp is missing but the important thing is that if you can discard the microseconds and anything beyond, the first 13 digits will give you a correct timestamp

处理此问题的通用方法是始终乘以毫秒并丢弃其余部分(javascript):

let time = Number((1278276905502403 * 1000).toString().substring(0, 13)) 
let Date = new Date(time).toString() 
// > "Sun Jul 04 2010 13:55:05 GMT-0700 (Pacific Daylight Time)"