Python-解析并将字符串转换为时间戳 [英] Python - Parsing and converting string into timestamp

查看:65
本文介绍了Python-解析并将字符串转换为时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的字符串: 2017-02-14T09:51:46.0​​00-0600

I have string in next format: 2017-02-14T09:51:46.000-0600

解析字符串并将其转换为时间戳的最佳方法是什么?我可以选择使用正则表达式或编写自己的函数进行解析,但是有任何内置方法可以帮助我吗?

What is the best approach to parse and convert string into timestamp? I have options to use regular expression or to write my own function for parsing, but are there any builtin methods which can help me?

推荐答案

第一部分将创建日期时间对象:

First part would be creating datetime object:

from datetime import datetime

date_string = "2017-02-14T09:51:46.000-0600"
# I'm using date_string[:-9] to skip ".000-0600"
format_date = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f%z'))

以下格式日期为:

print(format_date)
2017-02-14 09:51:46

时间戳是:

print(format_date.timestamp())
1487062306.0

这里很少澄清,在python 参考页上,您可以看到有关的定义我使用的'%Y-%m-%dT%H:%M:%S.%f%z')格式说明符.

Little clarification here, on python reference page, you can see definition for '%Y-%m-%dT%H:%M:%S.%f%z') format specifiers I used.

  • %Y :以世纪作为十进制数字的年份,例如1970、1988、2001、2013
  • %m :月份为零填充的十进制数字(例如01、02,...,12)
  • %d :每月的一天,以零填充的十进制数字(例如01、02,...,31)
  • %H :小时(24小时制)为零填充的十进制数字(例如00、01,...,23)
  • %M :以零填充的十进制数字表示(例如00、01,...,59)
  • %S :第二个,为零填充的十进制数字(例如00、01,...,59)
  • %f :微秒,十进制数字,左侧零填充(000000,000001,...,999999)
  • %z :UTC偏移量,格式为+ HHMM或-HHMM,如果对象是幼稚对象,则为空字符串(空或+ 0000,-0400,+ 1030)
  • %Y: Year with century as a decimal number, e.g. 1970, 1988, 2001, 2013
  • %m: Month as a zero-padded decimal number (e.g. 01, 02, ..., 12)
  • %d: Day of the month as a zero-padded decimal number (e.g. 01, 02, ..., 31)
  • %H: Hour (24-hour clock) as a zero-padded decimal number (e.g 00, 01, ..., 23)
  • %M: Minute as a zero-padded decimal number (e.g 00, 01, ..., 59)
  • %S: Second as a zero-padded decimal number (e.g. 00, 01, ..., 59)
  • %f: Microsecond as a decimal number, zero-padded on the left (000000, 000001, ..., 999999)
  • %z: UTC offset in the form +HHMM or -HHMM, empty string if the the object is naive, (empty or +0000, -0400, +1030)

这篇关于Python-解析并将字符串转换为时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆