datetime时间转字符串在我们的使用中,我们常常需要将时间转换为字符串,用来作为文件的名字或者用于加密字符的输出等等。例子:from datetime import datetime datetime.strftime(datetime.now(),"%Y-%m-%d %H:%M:%S")记忆方式也很简单,str from time字符转时间有时候我们需要将一个字符给转换为时间对象from datetime import datetime >>> datetime.strptime(‘2018-09-09’,"%Y-%m-%d")datetime.datetime(2018, 9, 9, 0, 0)时间戳的转换import time from datetime import datetime stamp = time.time()datetime.fromtimestamp(stamp)timedeltaimport datetimeprint(‘microseconds:’, datetime.timedelta(microseconds=1))print(‘milliseconds:’, datetime.timedelta(milliseconds=1))print(‘seconds :’, datetime.timedelta(seconds=1))print(‘minutes :’, datetime.timedelta(minutes=1))print(‘hours :’, datetime.timedelta(hours=1))print(‘days :’, datetime.timedelta(days=1))print(‘weeks :’, datetime.timedelta(weeks=1))加 就是 延后几秒; 减 就是提前几秒转换格式SymbolMeaningExample%aAbbreviated weekday name’Wed’%AFull weekday name’Wednesday’%wWeekday number: 0 (Sunday) through 6 (Saturday)‘3’%dDay of the month (zero padded)‘13’%bAbbreviated month name’Jan’%BFull month name’January’%mMonth of the year'01’%yYear without century'18’%YYear with century'2018’%HHour from 24-hour clock'17’%IHour from 12-hour clock'05’%pAM/PM’PM’%MMinutes'00’%SSeconds'00’%fMicroseconds'000000’%zUTC offset for time zone–aware objects’-0500’%ZTime zone name’EST’%jDay of the year'013’%WWeek of the year'02’%cDate and time representation for the current locale’Wed Jan 13 17:00:00 2016’%xDate representation for the current locale'01/13/16’%XTime representation for the current locale'17:00:00’%%A literal % character’%’tips工作中经常需要用到美国时间,做一个记录。 utc晚了8个小时,所以要减去即是美国时间datetime.strftime(datetime.utcnow()-timedelta(hours=8),’%Y-%m-%d %H:%M:%S’)参考《The Python3 Standard Library By Example》