且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python-解析并将字符串转换为时间戳

更新时间:2023-02-26 08:53:54

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

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)