Python's method of manipulating dates and times

  • 2020-04-02 13:28:12
  • OfStack

Datetime and the time standard library modules come to mind whenever and wherever we run into time related programming problems, and today we'll use their internal methods to detail python's methods for manipulating dates and times.
1. Converts the time of a string to a timestamp

 methods :
a = "2013-10-10 23:40:00"
# Convert it to a time array 
import time
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
# Convert to a timestamp :
timeStamp = int(time.mktime(timeArray))
timeStamp == 1381419600

2. Format 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 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. Convert the timestamp to the specified format date
Method 1: use localtime() to convert to a time array, and then format it into the desired format, such as:
timeStamp = 1381419600
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
otherStyletime == "2013-10-10 23:40:00"

Method 2:
import datetime
timeStamp = 1381419600
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
otherStyletime == "2013-10-10 23:40:00"

Gets the current time and converts to the specified date format
Method one:
import time
# Get the current time timestamp 
now = int(time.time())  -> This is a timestamp 
# Convert 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 2:
import datetime
# Get the current time 
now = datetime.datetime.now()  -> This is the time array format 
# Converts to the specified format :
otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")

5. Ways to get the time three days ago
import time
import datetime
# Get the date in the time array format first 
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))
# Convert to a timestamp :
timeStamp = int(time.mktime(threeDayAgo.timetuple()))
# Converts to other string formats :
otherStyleTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
 note :timedelta() The parameters are :days,hours,seconds,microseconds

6. Given a timestamp, calculate the days before that time
timeStamp = 1381419600
# To convert datetime
import datetime
import time
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
threeDayAgo = dateArray - datetime.timedelta(days = 3)
# reference 5, It can be converted to any other format 

Calculate the dates of yesterday and tomorrow in Python
>>> import datetime # Import the date time module 
>>> today = datetime.date.today() # Get today's date 
>>> print today # Output today's date 
2014-01-04 
>>> yesterday = today - datetime.timedelta(days=1) # The time difference is subtracted by today's date 1 Day, get yesterday's date 
>>> print yesterday
2014-01-03 
>>> tomorrow = today + datetime.timedelta(days=1) # Take the date of today plus the time difference 1 Day, get the date for tomorrow 
>>> print tomorrow
2014-01-05 
>>>
>>> print " Yesterday, :%s .   Today, :%s .   Tomorrow: %s" % (yesterday, today, tomorrow) # String concatenated output, here 3 The date of the day 

Yesterday :2014-01-03, today :2014-01-04, tomorrow: 2014-01-05
8. Python USES the time module to get the current time

#!/usr/bin/python
import time
print (time.strftime("%H:%M:%S"))
## 12 hour format ##
print (time.strftime("%I:%M:%S"))
# Output: 
#18:11:30
#6 : 11:30

9. A python program that prints out the current date
!/usr/bin/python
import time
## dd/mm/yyyy format 
print (time.strftime("%d/%m/%Y"))
# Output: 
11/03/2014

Use the datetime module to get the current date and time
#!/usr/bin/python
import datetime
i = datetime.datetime.now()
print (" The current date and time is  %s" % i)
print ("ISO The format of the date and time is  %s" % i.isoformat() )
print (" The current year is  %s" %i.year)
print (" The current month is  %s" %i.month)
print (" The current date is   %s" %i.day)
print ("dd/mm/yyyy  Format is   %s/%s/%s" % (i.day, i.month, i.year) )
print (" The current hour is  %s" %i.hour)
print (" The current minute is  %s" %i.minute)
print (" The second is   %s" %i.second)


Attachment: format parameters for date and time

%a  Days of the week 
%A  The full name of the day of the week 
%b  Short for month 
%B  The full name of the month 
%c  A time series of standard dates 
%C  The last two digits of the year 
%d  The day of the month in decimal notation 
%D  month / day / years 
%e  In a two-character field, the decimal number for the day of the month 
%F  years - month - day 
%g  The last two digits of the year, using the week-based year 
%G  Year points, using week-based years 
%h  The name of the month in short 
%H 24 Hours by the hour 
%I 12 Hours by the hour 
%j  The number of days of the year in decimal notation 
%m  A decimal month 
%M  The number of minutes in ten minutes 
%n  New line character 
%p  The local AM or PM Equivalent display of 
%r 12 Hours of time 
%R  Display hours and minutes: hh:mm
%S  The number of seconds in decimal 
%t  Horizontal tabs 
%T  Display time: hh:mm:ss
%u  The first day of the week is Monday   (the value from 0 to 6 , Monday for 0 ) 
%U  Week 1 of the year, make Sunday your first day 0 to 53 ) 
%V  For the week of the year, use the week-based year 
%w  Decimal represents the day of the week (value from 0 to 6 On Sunday 0 ) 
%W  Week of the year, make Monday your first day 0 to 53 ) 
%x  Standard date string 
%X  Standard time series 
%y  Decimal year without century (value from 0 to 99 ) 
%Y  Ten years with the century part 
%z . %Z  Time zone name, returns a null character if the time zone name cannot be obtained. 
%%  percent 


Related articles: