Convert Datetime to Unix Timestamp

Convert datetime to Unix timestamp and convert it back in python

What you missed here is timezones.

Presumably you've five hours off UTC, so 2013-09-01T11:00:00 local and 2013-09-01T06:00:00Z are the same time.

You need to read the top of the datetime docs, which explain about timezones and "naive" and "aware" objects.

If your original naive datetime was UTC, the way to recover it is to use utcfromtimestamp instead of fromtimestamp.

On the other hand, if your original naive datetime was local, you shouldn't have subtracted a UTC timestamp from it in the first place; use datetime.fromtimestamp(0) instead.

Or, if you had an aware datetime object, you need to either use a local (aware) epoch on both sides, or explicitly convert to and from UTC.

If you have, or can upgrade to, Python 3.3 or later, you can avoid all of these problems by just using the timestamp method instead of trying to figure out how to do it yourself. And even if you don't, you may want to consider borrowing its source code.

(And if you can wait for Python 3.4, it looks like PEP 341 is likely to make it into the final release, which means all of the stuff J.F. Sebastian and I were talking about in the comments should be doable with just the stdlib, and working the same way on both Unix and Windows.)

Converting to unix timestamp Python

Change

newDate = time.mktime(datetime.strptime(toDayDate, "%Y-%m-%d %H:%M:%S").timetuple())

to

newDate = time.mktime(datetime.timetuple())

as an example I did:

from datetime import datetime
from time import mktime
t = datetime.now()
unix_secs = mktime(t.timetuple())

and got unix_secs = 1488214742.0

Credit to @tarashypka- use t.utctimetuple() if you want the result in UTC (e.g. if your datetime object is aware of timezones)

How can I convert datetime to unix timestamp in python

%Z can't parse the timezone name PT - I suggest you skip parsing it and add it "manually" instead:

from datetime import datetime
import dateutil

news_date = "Mon, 15 Jun 2020 22:11:06 PT"

# parse string without the timezone:
news_date = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')

# add the timezone:
news_date = news_date.replace(tzinfo=dateutil.tz.gettz('US/Pacific'))

# extract POSIX (seconds since epoch):
news_date_posix = news_date.timestamp()
# 1592284266.0

if you have multiple strings with different timezones, you could use a dict to map the abbreviations to time zone names, e.g.

tzmapping = {'PT': 'US/Pacific'}
news_date = "Mon, 15 Jun 2020 22:11:06 PT"
# get appropriate timezone from string, according to tzmapping:
tz = dateutil.tz.gettz(tzmapping[news_date.split(' ')[-1]])
# parse string and add timezone:
news_date_datetime = datetime.strptime(news_date[:-3], '%a, %d %b %Y %H:%M:%S')
news_date_datetime = news_date_datetime.replace(tzinfo=tz)

How to convert current datetime into 13 digits Unix timestamp?

do it like this

import time
import datetime

d = datetime.datetime.now()
unixtime = datetime.datetime.timestamp(d)*1000

print(unixtime)

or you just use time.time()

pandas datetime to unix timestamp seconds

I think you misunderstood what the argument is for. The purpose of origin='unix' is to convert an integer timestamp to datetime, not the other way.

pd.to_datetime(1.547559e+09, unit='s', origin='unix') 
# Timestamp('2019-01-15 13:30:00')

Here are some options:

Option 1: integer division

Conversely, you can get the timestamp by converting to integer (to get nanoseconds) and divide by 109.

pd.to_datetime(['2019-01-15 13:30:00']).astype(int) / 10**9
# Float64Index([1547559000.0], dtype='float64')

Pros:

  • super fast

Cons:

  • makes assumptions about how pandas internally stores dates


Option 2: recommended by pandas

Pandas docs recommend using the following method:

# create test data
dates = pd.to_datetime(['2019-01-15 13:30:00'])

# calculate unix datetime
(dates - pd.Timestamp("1970-01-01")) // pd.Timedelta('1s')

[out]:
Int64Index([1547559000], dtype='int64')

Pros:

  • "idiomatic", recommended by the library

Cons:

  • unweildy
  • not as performant as integer division


Option 3: pd.Timestamp

If you have a single date string, you can use pd.Timestamp as shown in the other answer:

pd.Timestamp('2019-01-15 13:30:00').timestamp()
# 1547559000.0

If you have to cooerce multiple datetimes (where pd.to_datetime is your only option), you can initialize and map:

pd.to_datetime(['2019-01-15 13:30:00']).map(pd.Timestamp.timestamp)
# Float64Index([1547559000.0], dtype='float64')

Pros:

  • best method for a single datetime string
  • easy to remember

Cons:

  • not as performant as integer division

Convert Datetime to Unix timestamp

As Peter Halasz mentions in T-SQL DateTime to Unix Timestamp:

Converting a datetime to unix timestamp is easy, but involves error
prone typing the following:

@timestamp=DATEDIFF(second,{d '1970-01-01'},@datetime)

Where @datetime is the datetime value you want to convert. The {d
‘yyyy-mm-dd’} notation is an ODBC escape sequence.

The function:

CREATE FUNCTION UNIX_TIMESTAMP (
@ctimestamp datetime
)
RETURNS integer
AS
BEGIN
/* Function body */
declare @return integer

SELECT @return = DATEDIFF(SECOND,{d '1970-01-01'}, @ctimestamp)

return @return
END

Try it out now like below @O A:

SELECT UNIX_TIMESTAMP(GETDATE());

How to convert From DateTime to unix timestamp in Flutter or Dart in general

Darts DateTime has a property millisecondsSinceEpoch which should be what unix timestamp is as well.

DateTime.now().toUtc().millisecondsSinceEpoch

SQL converting date/time to unix timestamp

You can convert the string to a datetime using:

select convert(datetime, '2021.05.03 12:50:22')

You can then convert this to Unix epoch time (seconds since 1970-01-01) using:

select datediff(second, '1970-01-01', convert(datetime, '2021.05.03 12:50:22'))

Here is a db<>fiddle.



Related Topics



Leave a reply



Submit