Python date and time

Python programs can handle dates and times in many ways, and converting date formats is a common feature.

Python provides a time and calendar module that can be used to format dates and times.

The interval is a floating point decimal in seconds.

Each timestamp is expressed as how much time has elapsed since midnight (epoch) on January 1, 1970.

Python's time module has many functions to convert common date formats. For example, the function time.time() is used to obtain the current timestamp, as in the following example:

  

format date

#!/usr/bin/python

# -*- coding: UTF-8 -*-

import time


# Formatted as 2016-03-20 11:45:39

print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 

# Formatted as Sat Mar 28 22:24:24 2016

print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) 

  

# Convert format string to timestamp

a = "Sat Mar 28 22:24:24 2016"

print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))

The output of the above example is:

2016-04-07 10:25:09

Thu Apr 07 10:25:09 2016

1459175064.0

Time and date formatting symbols in python:

  • %y Two-digit year representation (00-99)
  • %Y Four-digit year representation (000-9999)
  • %m month (01-12)
  • %d day of the month (0-31)
  • %H 24-hour hour (0-23)
  • %I 12-hour clock (01-12)
  • %M minutes (00=59)
  • %S seconds (00-59)
  • %a local abbreviated weekday name
  • %A local full week name
  • %b local abbreviated month name
  • %B local full month name
  • %c Local corresponding date representation and time representation
  • %j 年内的一天(001-366)
  • %p 本地A.M.或P.M.的等价符
  • %U 一年中的星期数(00-53)星期天为星期的开始
  • %w 星期(0-6),星期天为星期的开始
  • %W 一年中的星期数(00-53)星期一为星期的开始
  • %x 本地相应的日期表示
  • %X 本地相应的时间表示
  • %Z 当前时区的名称
  • %% %号本身


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324819699&siteId=291194637