

Unix timestamps are commonly used for files in operating systems.
#Utc time plus or minus minutes code#
Using the below code will print them: In: for tz in pytz.all_timezones: print(tz) Out: Africa/Abidjan Africa/Accra Africa/Addis_Ababa (Only showing the first three as examples) Unix timestamp / Epoch time calculation If you are interested in the whole list of different time zones. The comparisons between dates are straightforward with usual comparison symbols: In: print(d (d2 +(timedelta(weeks=52*6)))) # d is more than 6 years (assume each year has 52 weeks) after d2? print(d != d2) # d2 is not the same date as d? print(d = d2) # d2 is the same date as d? Out: True False True False Time zones settingsĪnd we can also compare time in different time zones, such as Toronto and Shanghai: In: import pytz timezone = pytz.timezone("America/Toronto") dtz = timezone.localize(d) print(dtz.tzinfo) print(dtz) Out: America/Toronto 13:18:27.386763-05:00 In: shanghai_dt = dtz.astimezone(pytz.timezone("Asia/Shanghai")) print(shanghai_dt) Out: 02:18:27.386763+08:00 In: (dtz - shanghai_dt)/timedelta(days=1) # same datetimes Out: 0.0 Let’s do some “time travel” by different time intervals of second, minute, hour, day, week or year: In: print(d + timedelta(seconds=1)) # today + one second print(d + timedelta(minutes=1)) # today + one minute print(d + timedelta(hours=1)) # today + one hour print(d + timedelta(days=1)) # today + one day print(d + timedelta(weeks=1)) # today + one week print(d + timedelta(days=1)*365) # today + one year Out: 13:18:28.386763 13:19:27.386763 14:18:27.386763 13:18:27.386763 13:18:27.386763 13:18:27.386763 Datetime comparison In: date_diff = (d - d2)/timedelta(days=1) print('date_diff = years'.format(date_diff)) Out: date_diff = 3.8919300921728497 years Datetime plus/minus a certain period of time
/cloudfront-us-east-2.images.arcpublishing.com/reuters/EQV6PKTWYZKD5BVIHJDH7UY5QU.jpg)
We can also only print the difference of two datetimes in days, weeks or years, etc. The example below prints the difference in days (for example today and February 1st, 2016): In: from datetime import timedelta d = datetime.now() date_string = '' d2 = datetime.strptime(date_string, '%m/%d/%Y') print(d - d2) Out: 1420 days, 13:18:27.386763 In: print(d.strftime("%A %d/%m/%Y")) # date to string Out: Sunday String to date conversionīelow are examples showing two popular strings being converted to date format: In: date_string = ' 12:00PM' print(datetime.strptime(date_string, '%Y-%m-%d %I:%M%p')) Out: 12:00:00 In: date_string = '' d2 = datetime.strptime(date_string, '%m/%d/%Y') print(d2) Out: 00:00:00 Difference in datetime calculation
