Convert a column of datetimes to epoch in Python

convert the string to a datetime using to_datetime and then subtract datetime 1970-1-1 and call dt.total_seconds(): In [2]: import pandas as pd import datetime as dt df = pd.DataFrame({‘date’:[‘2011-04-24 01:30:00.000’]}) df Out[2]: date 0 2011-04-24 01:30:00.000 In [3]: df[‘date’] = pd.to_datetime(df[‘date’]) df Out[3]: date 0 2011-04-24 01:30:00 In [6]: (df[‘date’] – dt.datetime(1970,1,1)).dt.total_seconds() Out[6]: 0 1303608600 … Read more

How to extract epoch from LocalDate and LocalDateTime?

The classes LocalDate and LocalDateTime do not contain information about the timezone or time offset, and seconds since epoch would be ambigious without this information. However, the objects have several methods to convert them into date/time objects with timezones by passing a ZoneId instance. LocalDate LocalDate date = …; ZoneId zoneId = ZoneId.systemDefault(); // or: … Read more

PostgreSQL: how to convert from Unix epoch to date?

You use to_timestamp function and then cast the timestamp to date select to_timestamp(epoch_column)::date; More details: /* Current time */ select now(); — returns timestamp /* Epoch from current time; Epoch is number of seconds since 1970-01-01 00:00:00+00 */ select extract(epoch from now()); /* Get back time from epoch */ — Option 1 – use to_timestamp … Read more

python – datetime with timezone to epoch

To convert a datetime with timezone to epoch (POSIX timestamp): from datetime import datetime import pytz tz = pytz.timezone(‘CST6CDT’) # a datetime with timezone dt_with_tz = tz.localize(datetime(2012, 8, 28, 19, 33, 50), is_dst=None) # get timestamp ts = (dt_with_tz – datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() # -> 1346200430.0 It is how datetime.timestamp method is implemented for … Read more

Converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp: >>> import datetime >>> s = 1236472051807 / 1000.0 >>> datetime.datetime.fromtimestamp(s).strftime(‘%Y-%m-%d %H:%M:%S.%f’) ‘2009-03-08 09:27:31.807000’ %f directive is only supported by datetime.datetime.strftime, not by time.strftime. UPDATE Alternative using %, str.format: >>> import time >>> s, ms = divmod(1236472051807, 1000) # (1236472051, 807) >>> ‘%s.%03d’ % (time.strftime(‘%Y-%m-%d %H:%M:%S’, time.gmtime(s)), ms) ‘2009-03-08 00:27:31.807’ >>> ‘{}.{:03d}’.format(time.strftime(‘%Y-%m-%d %H:%M:%S’, … Read more