如何在Python中格式化日期和时间

2024-04-19 13:12:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个变量的值如下:

val='14/12/15 0000'

它是两位数的年/月/日小时数格式。你知道吗

我需要把这个转换成新纪元时间。你知道吗

我试过了

import datetime

datetime.datetime.strptime(val, "%y/%m/%d %HH%MM").strftime('%s')

我得到这个错误:

ValueError: time data '14/12/15 0000' does not match format '%y/%m/%d %HH%MM'

我做错什么了?你知道吗


Tags: importdatadatetimetime格式错误时间val
2条回答

小时(24小时)是%H,而不是%HH,分钟是%M,而不是%MM。你知道吗

datetime.datetime.strptime(val, "%y/%m/%d %H%M").strftime('%s')

您可以使用easy_date简化:

import date_converter
my_datetime = date_converter.string_to_string('14/12/15 0000', '%y/%m/%d %H%M', '%s')

或者直接将转换为时间戳:

import date_converter
timestamp = date_converter.string_to_timestamp('14/12/15 0000', '%y/%m/%d %H%M')

相关问题 更多 >