python時間フォーマット処理

5573 ワード

# -*- coding: utf-8 -*-
#    
import pytz
import datetime
pytz.country_timezones('cn') #      
#['Asia/Shanghai', 'Asia/Harbin', 'Asia/Chongqing', 'Asia/Urumqi', 'Asia/Kashgar']
tz = pytz.timezone('Asia/Shanghai') #    
print datetime.datetime.now(tz) #      
print datetime.datetime.strftime(datetime.datetime.now(tz),"%Y-%m-%d %H:%M:%S") #      

##########################   ##########################

from  datetime import datetime
import time
#      ,  string  
now_str = time.strftime("%Y-%m-%d %H:%M:%S") 
print (type(now_str))    
print now_str
print '---'

#      ,  datetime  
print (type(datetime.now()))    
print datetime.now()
print '---'

# string -> datetime
time_type = datetime.strptime(now_str, "%Y-%m-%d %H:%M:%S") 
print type(time_type)
print time_type
print '---'

# datetime -> string
str_type = datetime.strftime(time_type, "%Y-%m-%d %H:%M:%S") 
print type(str_type)
print str_type

#      
starttime = datetime.now()
endtime = datetime.now()
print (endtime - starttime).seconds

#   datetime  
new_dt = datetime(2005, 2, 16)
print type(new_dt)
print new_dt

#     ,    datetime,   datetime.datetime
yesterday_date = datetime.datetime.now() - datetime.timedelta(days=1)  
yesterday_str = datetime.datetime.strftime(yesterday_date, "%Y%m%d")

# datetime to timestamp
import time
int(time.mktime(dt.timetuple()))

# timestamp to datetime
dt = datetime.fromtimestamp(timestamp)

 
転載先:https://www.cnblogs.com/kennyhr/p/3837640.html