Created
November 26, 2016 15:22
-
-
Save libert-xyz/72fd12ef710cce5bc730f1428c2f20d2 to your computer and use it in GitHub Desktop.
Date and Time manipulation in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import pytz | |
tday = datetime.date.today() | |
bday = datime.date(2017,8,17) | |
#Example1 | |
#Time until my bday | |
till_bday = bday - tday #timedelta object | |
print(till_bday) | |
#Example2 | |
dt = datetime.datetime(2016,11,26,12,30,45,100000) | |
tdelta = datetime.timedelta(hours=13) | |
print(dt + tdelta) | |
#Example3 - No Timezone aware | |
dt_today = datetime.datetime.today() #2016-11-26 09:40:29.934950 Timezone = None | |
dt_now = datetime.datetime.now() #2016-11-26 09:40:34.211644 without Timezone | |
dt_utcnow = datetime.datetime.utcnow() #2016-11-26 14:40:38.180928 | |
print(dt_today) | |
print(dt_now) | |
print(dt_utcnow) | |
#Example4 - pytz | |
dt = datetime.datetime(2016,11,26,12,30,45, tzinfo=pytz.UTC) | |
dt_utcnow = datetime.datetime.now(tz=pytz.UTC) #2016-11-26 14:52:17.721137+00:00 | |
#from utc to eastern time | |
dt_east = dt_utcnow.astimezone(pytz.timezone('US/Eastern')) | |
#Example 5 from east to west | |
dt_east = datetime.datetime.now() | |
east_tz = pytz.timezone('US/Eastern') | |
dt_east = east_tz.localize(dt_east) | |
dt_west = dt_east.astimezone(pytz.timezone('US/Pacific')) | |
#Example 5 - ISO Format | |
dt = datetime.datetime.now(tz=pytz.timezone('US/Eastern')) | |
print(dt.strftime('%B %d, %Y')) #November 26, 2016 | |
#Example 6 - string to datetime | |
dt_str = 'November 26, 2016' | |
dt = datetime.datetime.strptime(dt_str, '%B %d, %Y') | |
#######Print all pytz timeZones############# | |
#for tz in pytz.all_timezones: | |
#print(tz) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment