赞
踩
把字符串转换为datetime的格式
项目 | 字符串的样子 |
---|---|
‘%m/%d/%Y %H:%M:%S’ | 2/3/2023 15:30:20 |
‘%m-%d-%Y %H-%M-%S’ | 2-3-2023 15-30-20 |
注意上面只是一个例子,年月日时分秒这些可以根据自己的数据来调整顺序,中间的连接符也是一样可以调整
from datetime import datetime, timedelta
time_str = '2/3/2023 15:30:20'
formated_time = datetime.strptime(time_str, '%m/%d/%Y %H:%M:%S')
__format__方法可以将datetime格式的时间,转化为想要的字符串,下面分别获得年、月,写上对应的时间格式,如%m/%d/%Y %H:%M:%S,可以获得年月日时分秒的字符串
project_first_day = dt.today()
curr_year = project_first_day.__format__("%Y")
curr_mon = project_first_day.__format__("%m")
将时间戳转换为datetime格式
project_start_day = dt.fromtimestamp(200755513)
final_time.timestamp() # final_time为datetime格式
问题:有12小时制的时间字符串,如2/16/2023 7:11:46 PM, 2/16/2023 12:05:06 AM,希望将这些字符串转换为时间戳,以存储到数据库
思路:
def transform_12sys_time_to_timestamp(self, time_in_12_sys):
'''
desc: transform time in 12 system to time stamp
@param time_in_12_sys: for example '4/6/2022 3:09:29 AM' '4/10/2022 5:48:55 PM'
return: the corresponding timestamp
'''
time_str = time_in_12_sys[0:-3]
am_pm_label = time_in_12_sys[-2:]
formated_time = datetime.strptime(time_str, '%m/%d/%Y %H:%M:%S')
final_time = formated_time if am_pm_label == 'AM' else (formated_time + timedelta(hours=12))
return final_time.timestamp()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。