【问题标题】:convert python timestamp into minutes using JavaScript react使用 JavaScript react 将 python 时间戳转换为分钟
【发布时间】:2019-08-30 19:43:05
【问题描述】:

我正在使用 python(3.7) 和 React 开发一个项目,其中我从 python 获得了一个 timestamp,需要在 react component 中显示它,并且需要将它显示为 minutes

这是我尝试过的:

{Math.round((new Date().getTime() - new Date(message.timestamp).getTime())/60000)} minutes ago

它显示为:

NaN minutes ago

如果我显示为:

{message.timestamp}

然后它返回:

2019-04-09 13:01:22.036902+00:00

那么,我怎样才能只显示来自 timestamp 的分钟数?

【问题讨论】:

  • 也许你想试试moment.js
  • 您的“时间戳”类型为String(ISO 格式)。您需要将其解析为Date。将字符串传递给Date 构造函数会创建一个无效的Date 对象,这就是您的计算失败NaN 的原因。
  • 我复制了你的代码并将{message.timestamp}替换为:2019-04-09 13:01:22.036902+00:00:jsfiddle.net/cwfeo517,它可以工作
  • 我猜你不能更改 python 代码而只是在 datetime 对象上使用 .minute ?示例:datetime.now().minute

标签: javascript python reactjs timestamp


【解决方案1】:

利用momentjs 库并根据需要格式化字符串

const a = "2019-04-09 13:01:22.036902+00:00"
console.log(moment(a).format('hh:mm A'))
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>

使用Date

var a = new Date("2019-04-09 13:01:22.036902+00:00")


a.getMinutes()

console.log("hours:"+a.getHours(),"minutes:"+a.getMinutes())

根据评论如果您正在寻找两个时间戳之间的差异,那么

const timediff= moment().diff(moment("2019-04-09 13:01:22.036902+00:00"),'minutes')


console.log('timediff',timediff)
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>

【讨论】:

  • 这不是 OP 所要求的,因为他想评估两个日期之间的差异
  • 正如他提到的问题how can I display only minutes from that timestamp 所以详细说明了如何显示小时和分钟。但现在都更新了
  • 我愿意投票,但使用原生 Date API 仍然没有差异 :)
【解决方案2】:

你可以试试

{Math.round((new Date().getTime() - Date.parse(String(message.timestamp)))/60000)} 分钟前

我觉得应该可以

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2013-02-08
    • 2018-05-15
    • 2014-04-30
    • 1970-01-01
    • 2018-07-04
    相关资源
    最近更新 更多