12 02 Combining Dates and Times - HannaAA17/Data-Scientist-With-Python-datacamp GitHub Wiki

Dates and Times

  • from datetime import datetime

Creating datetime objects from scratch

  • dt = datetime(year=2017, month=10, day=1, hour=15, minute=23, second=25, microsecond=500000)
  • or dt = datetime(2017, 10, 1, 15, 23, 25)

Replacing parts of a datetime

  • dt_hr = dt.replace(minute=0, second=0, microsecond=0)

Printing and Parsing datetimes

  • Printing: dt.strftime()
  • Parsing: dt.strptime()
Reference
%Y 4 digit year (0000-9999)
%m 2 digit month (1-12)
%d 2 digit day (1-31)
%H 2 digit hour (0-23)
%M 2 digit minute (0-59)
%S 2 digit second (0-59)
# Import the datetime class
from datetime import datetime

# Starting string, in YYYY-MM-DD HH:MM:SS format
s = '2017-02-03 00:00:01'

# Write a format string to parse s
fmt = '%Y-%m-%d %H:%M:%S'

# Create a datetime object d
d = datetime.strptime(s, fmt)

# Print d
print(d)

Unix timestamps

Datetimes are sometimes stored as Unix timestamps: the number of seconds since January 1, 1970. This is especially common with computer infrastructure, like the log files that websites keep when they get visitors.

  • datetime.fromtimestamp()
# Import datetime
from datetime import datetime

# Starting timestamps
timestamps = [1514665153, 1514664543]

# Datetime objects
dts = []

# Loop
for ts in timestamps:
  dts.append(datetime.fromtimestamp(ts))
  
# Print results
print(dts)  #[datetime.datetime(2017, 12, 30, 20, 19, 13), datetime.datetime(2017, 12, 30, 20, 9, 3)]

Working with duration

  • timedelta
    • substract datetimes to create a timedelta: duration.total_Seconds()
  • Create timedelta by hand
    • delta1 = timedelta(seconds=1)
    • delta1 = timedelta(days=1, seconds=1)
    • delta1 = timedelta(weeks=-1)
  • datetime +/- timedelta