Python how to manipulate date and time

Source: Internet
Author: User
Tags month name timedelta

often get a user submitted the current date, we need to use this date as the basis to return it the day before, the date of the following days or conversion operations. Python can be a very simple solution to these problems with date calculations .

No matter when and where, as long as we are programmed to encounter time-related problems, we have to think of the datetime and the standard library module, today we will use its internal methods, detailed Python operation date and time method.

1. Convert the time of a string to a timestamp

Method: A = "2013-10-10 23:40:00" #将其转换为时间数组import Timetimearray = Time.strptime (A, "%y-%m-%d%h:%m:%s") #转换为时间戳: TimeStamp = Int (Time.mktime (timearray)) TimeStamp = = 1381419600

2. Formatting changes

If a = "2013-10-10 23:40:00", want to change to a ="2013/10/10 23:40:00"
Method: Convert to a time array first and then to another format

Timearray = Time.strptime (A, "%y-%m-%d%h:%m:%s") Otherstyletime = Time.strftime ("%y/%m/%d%h:%m:%s", TimeArray)


3. Timestamp is converted to the specified format date
Method One: Use LocalTime () to convert to a time array, and then format to the desired format, such as:

TimeStamp = 1381419600timeArray = Time.localtime (timeStamp) otherstyletime = Time.strftime ("%y-%m-%d%h:%m:%s", Timearray) Otherstyletime = = "2013-10-10 23:40:00"

Method Two:

Import Datetimetimestamp = 1381419600dateArray = Datetime.datetime.utcfromtimestamp (timeStamp) Otherstyletime = Datearray.strftime ("%y-%m-%d%h:%m:%s") Otherstyletime = = "2013-10-10 23:40:00"

4. Get the current time and convert to the specified date format
Method One:

Import time# Gets the current time timestamp now = Int (Time.time ()), which is the timestamp # converted to another date format, such as: "%y-%m-%d%h:%m:%s" Timearray = Time.localtime ( TimeStamp) Otherstyletime = Time.strftime ("%y-%m-%d%h:%m:%s", Timearray)

Method Two:

Import datetime# Get current time now = Datetime.datetime.now () This is the time array format # conversion to the specified format: otherstyletime = Now.strftime ("%y-%m-%d%H :%m:%s ")

5. How to get the time three days ago

Import Timeimport datetime# Get the time array format First date Threedayago = (Datetime.datetime.now ()-Datetime.timedelta (days = 3)) #转换为时间戳: timeStamp = Int (Time.mktime (Threedayago.timetuple ())) #转换为其他字符串格式: Otherstyletime = Threedayago.strftime ("%y-%m-%d%H :%m:%s ") Note: The parameters of Timedelta () are: days,hours,seconds,microseconds

6. Given a timestamp, calculate the time of the day before the time

TimeStamp = 1381419600# First converted to datetimeimport datetimeimport Timedatearray = Datetime.datetime.utcfromtimestamp ( TimeStamp) Threedayago = Datearray-datetime.timedelta (days = 3) #参考5, can be converted to any other format


7. Use Python to calculate yesterday's and tomorrow's dates

>>> import datetime #导入日期时间模块 >>> today = Datetime.date.today () #获得今天的日期 >>> Print Today # Output today date 2015-09-05 >>> yesterday = Today-datetime.timedelta (Days=1) #用今天日期减掉时间差, parameter is 1 days, get yesterday's date >>> Print yesterday2015-09-06 >>> tomorrow = Today + Datetime.timedelta (Days=1) #用今天日期加上时间差, parameter is 1 days, get tomorrow's date >> > Print tomorrow2015-09-07 >>>>>> print "Yesterday:%s, today:%s, tomorrow:%s"% (Yesterday, today, tomorrow) #字符串拼接在一 From the output, this 3-day date

Yesterday: 2015-09-05, today: 2015-09-06, Tomorrow: 2015-09-07
8. Use the time module in Python to get the current times

#!/usr/bin/pythonimport Timeprint (Time.strftime ("%h:%m:%s")) # # hour format # #print (Time.strftime ("%i:%m:%s")) # : Output #18:11:30#6:11:30

9. Print out the current date of the Python program

!/usr/bin/python import time## dd/mm/yyyy format print (Time.strftime ("%d/%m/%y")) #输出: 11/03/2014

10. Use the DateTime module to get the current date and time

#!/usr/bin/pythonimport Datetimei = Datetime.datetime.now () print ("The current date and time is%s"% i) print ("Date and time in ISO format is%s"% I.isoform at ()) print ("Current year is%s"%i.year) print ("Current month is%s"%i.month) print ("Current date is%s"%i.day) print ("dd/mm/yyyy format is%s/%s/%s" % (I.day, I.month, i.year)) print ("Current hour is%s"%i.hour) print ("Current minute is%s"%i.minute) print ("Current seconds is%s"%i.second)

Attached: Date and time formatting parameters

%a Day of the week%a the full name of the day of the week%b month of the abbreviated%b month full name%c standard date of the time string%c year of the last two digits%d decimal representation of the month of the first few%d Month/day/year%e in two-character fields, decimal represents the number of days of the month%f year-month-day%g year of the last two digits, using the week-based year%g years, using the month name based on the week%h abbreviation%h 24-Hour Hour%i The 12-hour hour%j decimal indicates the number of minutes of the day of the year%m decimal representation of the month%m the minute of the%n New line character%p local AM or PM equivalent display%r 12 hour time%r display hours and minutes: hh:mm%s decimal seconds%t Horizontal tab%t Display hours/minute: hh:mm:ss%u days of the week, Monday for the first day (value from 0 to 6, Monday is 0)%u the week of the year, the Sunday as the first day (value from 0 to)%V the week of the year, using a week-based year%w decimal Day (value from 0 to 6, Sunday is 0)% In the first week of the year, the time string of Monday as the date string%x standard (value from 0 to the range)%x standard is%Y the decimal year without the Century (values from 0 to%Y) The 10 year%z,%z time zone name with the century part, and a null character if the time zone name cannot be obtained. Percent hundred percent semicolon


Python how to manipulate date and time

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.