drn9573 2017-01-12 15:47
浏览 196
已采纳

如何解析时间长度不同的字符串时间戳?

I have a slice of values holding timestamps of different length. Most of them look like this:

2006-01-02T15:04:05.000000Z

but some of them are shorter:

2006-01-02T15:04:05.00000Z
2006-01-02T15:04:05.0000Z

If I do:

str := dataSlice[j][0].(string)
layout := "2006-01-02T15:04:05.000000Z"
t, err := time.Parse(layout, str)

I get errors like:

parsing time "2016-10-23T02:38:45.25986Z" as "2006-01-02T15:04:05.000000Z": cannot parse "" as ".000000"
parsing time "2016-10-23T21:43:59.0175Z" as "2006-01-02T15:04:05.000000Z": cannot parse ".0175Z" as ".000000"

I want to parse them exactly like they originally are. How can I dynamically switch the layout corresponding to the length? (And why do the error messages differ?)

  • 写回答

2条回答 默认 最新

  • dqunzip3183 2017-01-12 16:08
    关注

    For time layouts, if the fractional seconds are optional, use 9 instead of 0 in the layout. For example, 2006-01-02T15:04:05.00000Z matches only times with 5 digits after the decimal place. However, 2006-01-02T15:04:05.9Z matches a time with any number of digits after the decimal, including zero.

    https://play.golang.org/p/QMD28aqv9E

    The Time.Format documentation provides examples, the last one of which explains this behavior.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)