Skip to content

Instantly share code, notes, and snippets.

@jmquintana79
Last active February 14, 2018 01:22
Show Gist options
  • Save jmquintana79/f65233161afaeaa34346 to your computer and use it in GitHub Desktop.
Save jmquintana79/f65233161afaeaa34346 to your computer and use it in GitHub Desktop.
datetime library use
"""
class datetime.date
An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect.
Attributes: year, month, and day.
class datetime.time
An idealized time, independent of any particular day, assuming that every day has exactly 24*60*60 seconds (there is no notion of “leap seconds” here).
Attributes: hour, minute, second, microsecond, and tzinfo.
class datetime.datetime
A combination of a date and a time.
Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo.
class datetime.timedelta
A duration expressing the difference between two date, time, or datetime instances to microsecond resolution.
class datetime.tzinfo
An abstract base class for time zone information objects. These are used by the datetime and time classes to provide a customizable notion of time adjustment (for example, to account for time zone and/or daylight saving time).
"""
from datetime import datetime
# CREATE DATETIME OBJECT
date1 = datetime(2011, 4, 1) # 2011-04-01 00:00:00
datetime1 = datetime(2011, 4, 1, 16, 8, 18, 445529) # 2011-04-01 16:08:18.445529
now = datetime.now() # current datetime
# DATETIME OBJECT TO STRING
sdate1 = date1.strftime("%Y-%m-%d %H:%M:%S") # FORMAT: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
# DATE STRING TO DATETIME OBJECT
date = datetime.strptime(sdate, '%Y-%m-%dT%H:%M:%SZ')
# numpy.datetime64 TO DATETIME OBJECT
date = pd.Timestamp(datenp64).to_pydatetime()
# ADD STEP TO DATETIME OBJECT
from datetime import datetime,timedelta
date1 = datetime(2014,1,1)
date2 = date1 + timedelta(days=2)
print date1,date2 # 2014-01-01 00:00:00 2014-01-03 00:00:00
# TIMEDELTA OBJECT TO NUMBER
td = date2 - date1
days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60
## CREATE LIST OF DATETIME OBJECT BETWEEN TWO DATETIMES
# Monthly
def months_between(start,end):
from datetime import datetime,timedelta
months = []
cursor = start
while cursor <= end:
newcursor = datetime(cursor.year,cursor.month,1)
if newcursor not in months:
months.append(newcursor)
cursor += timedelta(weeks=1)
newcursor = datetime(cursor.year,cursor.month,1)
months.append(newcursor)
return months
# Daily
ldatetimes = [ datei+timedelta(days=iday) for iday in range((datef-datei).days+1)]
# Hourly
ldatetimes = [ datei+timedelta(hours=ihour) for ihour in range(((datef-datei).days+1)*24)]
# 10 minutes
l10dt = [ dti+timedelta(seconds=i10min*10.*60.) for i10min in range(int(int((dtf-dti).total_seconds()/60.)/10.)+1)]
## UTC TO LOCAL TIME
from datetime import datetime
from dateutil import tz
# METHOD 1: Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')
# METHOD 2: Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
central = utc.astimezone(to_zone)
# calculate temporal resolution for a list of dates (in minutes)
tresol = int(np.mean([int((idate - ldates[i]).seconds/60.) for i,idate in enumerate(ldates[1:])]))
## combine date and time object
from datetime import datetime
datetime.combine(datetime.date(2011, 1, 1), datetime.time(10, 23))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment