码迷,mamicode.com
首页 > 其他好文 > 详细

由“闰年”判断想到的日期与字符串间的转换

时间:2020-01-10 10:58:56      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:mda   calendar   isl   false   localtime   返回   struct   class   min   

一、时间字符串格式转化:

1、时间格式的字符串转时间

  from time import strptime

  >>> s_time = strptime("2020-01-10 09:29:15", "%Y-%m-%d %H:%M:%S")

  >>> print(s_time)
  time.struct_time(tm_year=2020, tm_mon=1, tm_mday=10, tm_hour=9, tm_min=29, tm_sec=15, tm_wday=4, tm_yday=10, tm_isdst=-1)

  >>> print(s_time.tm_year)

  2020

 

  >>> s_time = strptime("2020-01", "%Y-%m")

  >>> print(s_time)
  time.struct_time(tm_year=2020, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=1, tm_isdst=-1)
  >>> print(s_time.tm_year)
  2020

2、时间转字符串

  >>> from time import strptime, strftime, localtime

  >>> print(localtime())
  time.struct_time(tm_year=2020, tm_mon=1, tm_mday=10, tm_hour=9, tm_min=35, tm_sec=42, tm_wday=4, tm_yday=10, tm_isdst=0)
  >>> print(localtime().tm_year, localtime().tm_mday)
  2020 10

  >>> print(type(strftime("%Y-%m-%d %H:%M:%S", localtime())))
  <class ‘str‘>

  >>> print(strftime("%m-%d-%Y %H:%M:%S", localtime()))
  01-10-2020 09:42:49
  >>> print(type(strftime("%m-%d-%Y %H:%M:%S", localtime())))
  <class ‘str‘>

二、闰年判断

  import calendar

  from datetime import date

  from time import strptime, strftime, localtime

  calendar中的 isleap可以返回True(闰年)和False(不是闰年)

  >>> print(calendar.isleap(2012))

  True

  >>> print(calendar.isleap(date.today().year))
  True

  >>> print(calendar.isleap(localtime().tm_year))
  True

  ss = "2013"

  >>> print(calendar.isleap(datetime.datetime.strptime(ss, "%Y").year))
  False

由“闰年”判断想到的日期与字符串间的转换

标签:mda   calendar   isl   false   localtime   返回   struct   class   min   

原文地址:https://www.cnblogs.com/xinyu602/p/12174497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!