time和datetime模块

傷城~ 2021-09-20 01:46 528阅读 0赞

1.在Python中表示时间的方式

1.1时间戳

时间戳(timestamp)方式:通常来说,时间戳表示从1970年1月1日00:00:00开始按秒计算的偏移量。运行type(time.time())返回float类型
UTC (Coordinated Universal Time,世界协调时)即格林威治天文时间,世界标准时间。在中国为UTC+8。DST(Daylight Saving Time)即夏令时

import time
type(time.time())

print(time.time())
1557046718.6016247

1.2.格式化的时间字符串

“2019-05-05”

1.3.元组

元组(struct_time)方式共九个元素。返回struct_time的函数主要有gmtime(),localtime(),strptime()。下面列出这种方式元组中的几个元素

  1. 索引(Index 属性(Attribute 值(Values
  2. 0 tm_year(年) 比如2011
  3. 1 tm_mon(月) 1 - 12
  4. 2 tm_mday(日) 1 - 31
  5. 3 tm_hour(时) 0 - 23
  6. 4 tm_min(分) 0 - 59
  7. 5 tm_sec(秒) 0 - 61
  8. 6 tm_wdayweekday 0 - 60表示周日)
  9. 7 tm_yday(一年中的第几天) 1 - 366
  10. 8 tm_isdst(是否是夏令时) 默认为-1

2.time模块的方法

  • time.localtime([secs]):将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。

    time.localtime()
    time.struct_time(tm_year=2019, tm_mon=5, tm_mday=5, tm_hour=17, tm_min=15, tm_sec=43, tm_wday=6, tm
    _yday=125, tm_isdst=0)
    time.localtime()
    time.struct_time(tm_year=2019, tm_mon=4, tm_mday=25, tm_hour=23, tm_min=57, tm_sec=32, tm_wday=3, tm_yday=115, tm_isdst=0)
    a.tm_year
    2019
    ‘%s-%s-%s’%(a.tm_year,a.tm_mon,a.tm_mday)
    ‘2019-4-26’

  • time.gmtime([secs]):和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time。0时区的时间+8小时是utc+8的时间

    time.gmtime()
    time.structtime(tm_year=2019, tm_mon=5, tm_mday=5, tm_hour=9, tm_min=20, tm_sec=41, tm_wday=6, tm
    yday=125, tm_isdst=0)

  • time.time():返回当前时间的时间戳。

    time.time()
    1557048269.2991927

  • time.mktime(t):将一个struct_time转化为时间戳。

    time.mktime(time.localtime())
    1557048434.0

  • time.sleep(secs):线程推迟指定的时间运行。单位为秒。

    time.sleep(2)

  • time.asctime([t]):把一个表示时间的元组或者struct_time表示为这种形式:’Sun Oct 1 12:04:38 2017’。如果没有参数,将会将time.localtime()作为参数传入。

    time.asctime(time.localtime())
    ‘Sun May 5 17:30:00 2019’

  • time.ctime([secs]):把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于time.asctime(time.localtime(secs))。

    time.ctime(time.time())
    ‘Sun May 5 17:34:26 2019’

  • time.strftime(format[, t]):把一个代表时间的元组或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。

    time.strftime(“%Y-%m-%d %X”, time.localtime())
    ‘2019-05-05 17:37:35’

  • time.strptime(string[, format]):把一个格式化时间字符串转化为struct_time。实际上它和strftime()是逆操作。

    time.strptime(‘2019-05-05 17:37:35’, “%Y-%m-%d %X”)
    time.struct_time(tm_year=2019, tm_mon=5, tm_mday=5, tm_hour=17, tm_min=37, tm_sec=35, tm_wday=6, tm
    _yday=125, tm_isdst=-1)

time和datetime模块

字符串转时间格式对应表

  1. Meaning Notes
  2. %a Locales abbreviated weekday name.
  3. %A Locales full weekday name.
  4. %b Locales abbreviated month name.
  5. %B Locales full month name.
  6. %c Locales appropriate date and time representation.
  7. %d Day of the month as a decimal number [01,31].
  8. %H Hour (24-hour clock) as a decimal number [00,23].
  9. %I Hour (12-hour clock) as a decimal number [01,12].
  10. %j Day of the year as a decimal number [001,366].
  11. %m Month as a decimal number [01,12].
  12. %M Minute as a decimal number [00,59].
  13. %p Locales equivalent of either AM or PM. (1)
  14. %S Second as a decimal number [00,61]. (2)
  15. %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
  16. %w Weekday as a decimal number [0(Sunday),6].
  17. %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
  18. %x Locales appropriate date representation.
  19. %X Locales appropriate time representation.
  20. %y Year without century as a decimal number [00,99].
  21. %Y Year with century as a decimal number.
  22. %z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].
  23. %Z Time zone name (no characters if no time zone exists).
  24. %% A literal '%' character.
  25. >>> time.strftime("%a",time.localtime())
  26. 'Sun'
  27. >>> time.strftime("%A",time.localtime())
  28. 'Sunday'
  29. >>> time.strftime("%b",time.localtime())
  30. 'May'
  31. >>> time.strftime("%B",time.localtime())
  32. 'May'
  33. >>> time.strftime("%c",time.localtime())
  34. 'Sun May 5 17:54:45 2019'
  35. >>> time.strftime("%C",time.localtime())
  36. '20'
  37. >>> time.strftime("%d",time.localtime())
  38. '05'
  39. >>> time.strftime("%D",time.localtime())
  40. '05/05/19'
  41. >>> time.strftime("%H",time.localtime())
  42. '17'
  43. >>> time.strftime("%h",time.localtime())
  44. 'May'
  45. >>> time.strftime("%I",time.localtime())
  46. '05'
  47. >>> time.strftime("%i",time.localtime())
  48. Traceback (most recent call last):
  49. File "<stdin>", line 1, in <module>
  50. ValueError: Invalid format string
  51. >>> time.strftime("%j",time.localtime())
  52. '125'
  53. >>> time.strftime("%m",time.localtime())
  54. '05'
  55. >>> time.strftime("%M",time.localtime())
  56. '57'
  57. >>> time.strftime("%p",time.localtime())
  58. 'PM'
  59. >>> time.strftime("%S",time.localtime())
  60. '22'
  61. >>> time.strftime("%U",time.localtime())
  62. '18'
  63. >>> time.strftime("%W",time.localtime())
  64. '17'
  65. >>> time.strftime("%w",time.localtime())
  66. '0'
  67. >>> time.strftime("%x",time.localtime())
  68. '05/05/19'
  69. >>> time.strftime("%X",time.localtime())
  70. '17:58:54'
  71. >>> time.strftime("%y",time.localtime())
  72. '19'
  73. >>> time.strftime("%Y",time.localtime())
  74. '2019'
  75. >>> time.strftime("%Z",time.localtime())
  76. '?D1¨²¡À¨º¡Á?¨º¡À??'
  77. >>> time.strftime("%%",time.localtime())
  78. '%'
  79. >>>

3.datetime模块

  1. datetime.date:表示日期的类。常用的属性有year, month, day
  2. datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond
  3. datetime.datetime:表示日期时间。
  4. datetime.timedelta:表示时间间隔,即两个时间点之间的长度。
  5. datetime.tzinfo:与时区有关的相关信息。(这里不详细充分讨论该类,可以参考python手册)
  6. "需要记住的"
  7. 1.d=datetime.datetime.now() 返回当前的datetime日期类型
  8. d.timestamp(),d.today(), d.year,d.timetuple()等方法可以调用
  9. #!/usr/bin/env python
  10. # -*- coding:utf-8 -*-
  11. # Author: vita
  12. import datetime
  13. d = datetime.datetime.now()
  14. print(d)
  15. print("d.timestamp()",d.timestamp())
  16. print("d.today()",d.today())
  17. print("d.year",d.year)
  18. print("d.timetuple()",d.timetuple())
  19. E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
  20. 2019-05-05 18:11:52.005561
  21. d.timestamp() 1557051112.005561
  22. d.today() 2019-05-05 18:11:52.005561
  23. d.year 2019
  24. d.timetuple() time.struct_time(tm_year=2019, tm_mon=5, tm_mday=5, tm_hour=18, tm_min=11, tm_sec=52, tm_wday=6, tm_yday=125, tm_isdst=-1)
  25. Process finished with exit code 0
  26. 2.datetime.date.fromtimestamp(时间戳)把时间戳转换为datetime日期类型
  27. >>> datetime.date.fromtimestamp(1557051112.005561)
  28. datetime.date(2019, 5, 5)
  29. 3.时间运算
  30. >>> datetime.datetime.now()
  31. datetime.datetime(2017, 10, 1, 12, 53, 11, 821218)
  32. >>> datetime.datetime.now() + datetime.timedelta(4) #当前时间 +4天
  33. datetime.datetime(2017, 10, 5, 12, 53, 35, 276589)
  34. >>> datetime.datetime.now() + datetime.timedelta(hours=4) #当前时间+4小时
  35. datetime.datetime(2017, 10, 1, 16, 53, 42, 876275)
  36. 4.时间替换
  37. #!/usr/bin/env python
  38. # -*- coding:utf-8 -*-
  39. # Author: vita
  40. import datetime
  41. d = datetime.datetime.now()
  42. print(d.replace(year=2020,month=11,day=30))
  43. print("d.timetuple()",d.timetuple())
  44. E:\PythonProject\python-test\venvP3\Scripts\python.exe E:/PythonProject/python-test/BasicGrammer/test.py
  45. 2020-11-30 18:16:59.517815
  46. d.timetuple() time.struct_time(tm_year=2019, tm_mon=5, tm_mday=5, tm_hour=18, tm_min=16, tm_sec=59, tm_wday=6, tm_yday=125, tm_isdst=-1)
  47. Process finished with exit code 0

转载于:https://blog.51cto.com/10983441/2389382

发表评论

表情:
评论列表 (有 0 条评论,528人围观)

还没有评论,来说两句吧...

相关阅读

    相关 timedatetime模块

    1.在Python中表示时间的方式 1.1时间戳 > 时间戳(timestamp)方式:通常来说,时间戳表示从1970年1月1日00:00:00开始按秒计算的偏移量