How can I translate dates and times from natural language to datetime? [closed]

parsedatetime – Python module that is able to parse ‘human readable’ date/time expressions. #!/usr/bin/env python from datetime import datetime import parsedatetime as pdt # $ pip install parsedatetime cal = pdt.Calendar() now = datetime.now() print(“now: %s” % now) for time_string in [“tomorrow at 6am”, “next moday at noon”, “2 min ago”, “3 weeks ago”, “1 … Read more

How to make a timezone aware datetime object

In general, to make a naive datetime timezone-aware, use the localize method: import datetime import pytz unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0) aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC) now_aware = pytz.utc.localize(unaware) assert aware == now_aware For the UTC timezone, it is not really necessary to use localize since … Read more

Changing the formatting of a datetime axis in matplotlib

import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates # sample data N = 30 drange = pd.date_range(“2014-01″, periods=N, freq=”MS”) np.random.seed(365) # for a reproducible example of values values = {‘values’:np.random.randint(1,20,size=N)} df = pd.DataFrame(values, index=drange) fig, ax = plt.subplots() ax.plot(df.index, df.values) ax.set_xticks(df.index) # use formatters to specify major … Read more

How to convert a UTC datetime to a local datetime using only standard library?

In Python 3.3+: from datetime import datetime, timezone def utc_to_local(utc_dt): return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None) In Python 2/3: import calendar from datetime import datetime, timedelta def utc_to_local(utc_dt): # get integer timestamp to avoid precision lost timestamp = calendar.timegm(utc_dt.timetuple()) local_dt = datetime.fromtimestamp(timestamp) assert utc_dt.resolution >= timedelta(microseconds=1) return local_dt.replace(microsecond=utc_dt.microsecond) Using pytz (both Python 2/3): import pytz local_tz = pytz.timezone(‘Europe/Moscow’) # … Read more

How to calculate the time interval between two time strings

Yes, definitely datetime is what you need here. Specifically, the datetime.strptime() method, which parses a string into a datetime object. from datetime import datetime s1 = ’10:33:26′ s2 = ’11:15:49′ # for example FMT = ‘%H:%M:%S’ tdelta = datetime.strptime(s2, FMT) – datetime.strptime(s1, FMT) That gets you a timedelta object that contains the difference between the … Read more

How to make a timezone aware datetime object in Python?

In general, to make a naive datetime timezone-aware, use the localize method: import datetime import pytz unaware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0) aware = datetime.datetime(2011, 8, 15, 8, 15, 12, 0, pytz.UTC) now_aware = pytz.utc.localize(unaware) assert aware == now_aware For the UTC timezone, it is not really necessary to use localize since … Read more

Calculate Time Difference Between Two Pandas Columns in Hours and Minutes

Pandas timestamp differences returns a datetime.timedelta object. This can easily be converted into hours by using the *as_type* method, like so import pandas df = pandas.DataFrame(columns=[‘to’,’fr’,’ans’]) df.to = [pandas.Timestamp(‘2014-01-24 13:03:12.050000’), pandas.Timestamp(‘2014-01-27 11:57:18.240000’), pandas.Timestamp(‘2014-01-23 10:07:47.660000’)] df.fr = [pandas.Timestamp(‘2014-01-26 23:41:21.870000’), pandas.Timestamp(‘2014-01-27 15:38:22.540000’), pandas.Timestamp(‘2014-01-23 18:50:41.420000’)] (df.fr-df.to).astype(‘timedelta64[h]’) to yield, 0 58 1 3 2 8 dtype: float64

Convert DataFrame column type from string to datetime

The easiest way is to use to_datetime: df[‘col’] = pd.to_datetime(df[‘col’]) It also offers a dayfirst argument for European times (but beware this isn’t strict). Here it is in action: In [11]: pd.to_datetime(pd.Series([’05/23/2005′])) Out[11]: 0 2005-05-23 00:00:00 dtype: datetime64[ns] You can pass a specific format: In [12]: pd.to_datetime(pd.Series([’05/23/2005′]), format=”%m/%d/%Y”) Out[12]: 0 2005-05-23 dtype: datetime64[ns]