python 时间戳转日期 不自动补零 without zero-padding


1. 时间戳转日期

  • 代码
import time
timestamp = 1568171336
time_format = "%Y-%m-%d %H:%M:%S"
time_local = time.localtime(timestamp)
new_date = time.strftime(time_format, time_local)
print(new_date)
  • 结果
2019-09-11 11:08:56

2. 不自动补零

对于Linux 需要在字段类型前加上 -
对于win 需要再字段类型前加上 #

  • 代码示例
import time
timestamp = 1568171336
time_format = "%Y-%#m-%#d %H:%M:%S"
time_local = time.localtime(timestamp)
new_date = time.strftime(time_format, time_local)
print(new_date)
  • 结果
2019-9-11 11:08:56

来自 Python datetime formatting without zero-padding

Accepted answer not a proper solution (IMHO) The proper documented methods:

In Linux "#" is replaced by "-":

%-d, %-H, %-I, %-j, %-m, %-M, %-S, %-U, %-w, %-W, %-y, %-Y

In Windows "-" is replaced by "#":

%#d, %#H, %#I, %#j, %#m, %#M, %#S, %#U, %#w, %#W, %#y, %#Y

  • Linux
mydatetime.strftime('%-m/%d/%Y %-I:%M%p')
  • Windows
mydatetime.strftime('%#m/%d/%Y %#I:%M%p')


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM