How to convert date and time string to POSIX time? - python

I have two string :
date = '2017-05-09'
time = '19:28'
How do I convert this to posix time ?

You can process as follow:
Convert the string date and time to datetime.datetime instance.
Convert this instance to posix time:
import datetime
import time
my_date = '2017-05-09'
my_time = '19:28'
dt = datetime.datetime.strptime(my_date + " " + my_time, "%Y-%m-%d %H:%M")
posix_dt = time.mktime(dt.timetuple())

You may want to use the datetime library. Also, keep in mind that the two methods presented below expect local time.
With
>>> date = '2017-05-09'
>>> time_ = '19:28'
For 2.7.+ versions (may be lower versions also) of python, you first have to turn your string into a datetime object
>>> import datetime as dt
>>> date_object = dt.datetime.strptime('{d} {t}'.format(d=date, t=time_),
"%Y-%m-%d %H:%M")
>>> date_object
datetime.datetime(2017, 5, 9, 19, 28)
Note that I changed your variable time into time_, so as not to create conflicts of name afterward. Getting a posix time is easy to do with date_object
>>> import time
>>> time.mktime(date_object.timetuple())
1494350880.0 #Given my local time !
For 3.+ versions of python, it is even more direct than above
>>> import datetime as dt
>>> dt.datetime.strptime('{d} {t}'.format(d=date, t=time_),
'%Y-%m-%d %H:%M').timestamp()
1494350880.0 #Given my local time !

Related

convert unix timestamp in milliseconds to UTC time & date formatting python3 [duplicate]

I have a Python datetime object that I want to convert to unix time, or seconds/milliseconds since the 1970 epoch.
How do I do this?
It appears to me that the simplest way to do this is
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
def unix_time_millis(dt):
return (dt - epoch).total_seconds() * 1000.0
In Python 3.3, added new method timestamp:
import datetime
seconds_since_epoch = datetime.datetime.now().timestamp()
Your question stated that you needed milliseconds, which you can get like this:
milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000
If you use timestamp on a naive datetime object, then it assumed that it is in the local timezone. Use timezone-aware datetime objects if this is not what you intend to happen.
>>> import datetime
>>> # replace datetime.datetime.now() with your datetime object
>>> int(datetime.datetime.now().strftime("%s")) * 1000
1312908481000
Or the help of the time module (and without date formatting):
>>> import datetime, time
>>> # replace datetime.datetime.now() with your datetime object
>>> time.mktime(datetime.datetime.now().timetuple()) * 1000
1312908681000.0
Answered with help from: http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Documentation:
time.mktime
datetime.timetuple
You can use Delorean to travel in space and time!
import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch
http://delorean.readthedocs.org/en/latest/quickstart.html
This is how I do it:
from datetime import datetime
from time import mktime
dt = datetime.now()
sec_since_epoch = mktime(dt.timetuple()) + dt.microsecond/1000000.0
millis_since_epoch = sec_since_epoch * 1000
Recommendedations from the Python 2.7 docs for the time module
from datetime import datetime
from calendar import timegm
# Note: if you pass in a naive dttm object it's assumed to already be in UTC
def unix_time(dttm=None):
if dttm is None:
dttm = datetime.utcnow()
return timegm(dttm.utctimetuple())
print "Unix time now: %d" % unix_time()
print "Unix timestamp from an existing dttm: %d" % unix_time(datetime(2014, 12, 30, 12, 0))
Here's another form of a solution with normalization of your time object:
def to_unix_time(timestamp):
epoch = datetime.datetime.utcfromtimestamp(0) # start of epoch time
my_time = datetime.datetime.strptime(timestamp, "%Y/%m/%d %H:%M:%S.%f") # plugin your time object
delta = my_time - epoch
return delta.total_seconds() * 1000.0
>>> import datetime
>>> import time
>>> import calendar
>>> #your datetime object
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 3, 19, 13, 0, 9, 351812)
>>> #use datetime module's timetuple method to get a `time.struct_time` object.[1]
>>> tt = datetime.datetime.timetuple(now)
>>> tt
time.struct_time(tm_year=2013, tm_mon=3, tm_mday=19, tm_hour=13, tm_min=0, tm_sec=9, tm_wday=1, tm_yday=78, tm_isdst=-1)
>>> #If your datetime object is in utc you do this way. [2](see the first table on docs)
>>> sec_epoch_utc = calendar.timegm(tt) * 1000
>>> sec_epoch_utc
1363698009
>>> #If your datetime object is in local timeformat you do this way
>>> sec_epoch_loc = time.mktime(tt) * 1000
>>> sec_epoch_loc
1363678209.0
[1] http://docs.python.org/2/library/datetime.html#datetime.date.timetuple
[2] http://docs.python.org/2/library/time.html
A bit of pandas code:
import pandas
def to_millis(dt):
return int(pandas.to_datetime(dt).value / 1000000)
import time
seconds_since_epoch = time.mktime(your_datetime.timetuple()) * 1000
A lot of these answers don't work for python 2 or don't preserve the milliseconds from the datetime. This works for me
def datetime_to_ms_epoch(dt):
microseconds = time.mktime(dt.timetuple()) * 1000000 + dt.microsecond
return int(round(microseconds / float(1000)))
Here is a function I made based on the answer above
def getDateToEpoch(myDateTime):
res = (datetime.datetime(myDateTime.year,myDateTime.month,myDateTime.day,myDateTime.hour,myDateTime.minute,myDateTime.second) - datetime.datetime(1970,1,1)).total_seconds()
return res
You can wrap the returned value like this : str(int(res))
To return it without a decimal value to be used as string or just int (without the str)
This other solution for covert datetime to unixtimestampmillis.
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long GetCurrentUnixTimestampMillis()
{
DateTime localDateTime, univDateTime;
localDateTime = DateTime.Now;
univDateTime = localDateTime.ToUniversalTime();
return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
}

How can i add 7 hours into api_time? [duplicate]

I am able to get the current time as below:
from datetime import datetime
str(datetime.now())[11:19]
Result
'19:43:20'
Now, I am trying to add 9 hours to the above time, how can I add hours to current time in Python?
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as #eumiro has pointed out in comments - strftime
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime and strftime behavior to better understand how python processes dates and time field
This works for me working with seconds not hours and also using a function to convert back to UTC time.
from datetime import timezone, datetime, timedelta
import datetime
def utc_converter(dt):
dt = datetime.datetime.now(timezone.utc)
utc_time = dt.replace(tzinfo=timezone.utc)
utc_timestamp = utc_time.timestamp()
return utc_timestamp
# create start and end timestamps
_now = datetime.datetime.now()
str_start = str(utc_converter(_now))
_end = _now + timedelta(seconds=10)
str_end = str(utc_converter(_end))
This is an answer which is significant for nowadays (python 3.9 or later).
Use strptime to create a datetime object from the timestring. Add 9 hours with timedelta, and match the time format with the timestring you have.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
#You can then apply custom time formatting as well as a timezone.
TIMEZONE = [Add a timezone] #https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
custom_time_format = "%H:%M"
time_modification = datetime.fromtimestamp(timestring.timestamp(), ZoneInfo(TIMEZONE)).__format__(custom_time_format)
While I think it's more meaningful to apply a timezone, you don't necessarily need to, so you can also simply do that:
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
time_modification = datetime.fromtimestamp(timestring.timestamp())
datetime
https://docs.python.org/3/library/datetime.html
strftime-and-strptime-format-codes
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
timedelta
https://docs.python.org/3/library/datetime.html#datetime.timedelta
zoneinfo
https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo

Python - Get Yesterday's date as a string in YYYY-MM-DD format

As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.
datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
example:
In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
An alternative answer that uses today() method to calculate current date and then subtracts one using timedelta(). Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday

How to add hours to current time in python

I am able to get the current time as below:
from datetime import datetime
str(datetime.now())[11:19]
Result
'19:43:20'
Now, I am trying to add 9 hours to the above time, how can I add hours to current time in Python?
from datetime import datetime, timedelta
nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)
And then use string formatting to get the relevant pieces:
>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'
If you're only formatting the datetime then you can use:
>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'
Or, as #eumiro has pointed out in comments - strftime
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime and strftime behavior to better understand how python processes dates and time field
This works for me working with seconds not hours and also using a function to convert back to UTC time.
from datetime import timezone, datetime, timedelta
import datetime
def utc_converter(dt):
dt = datetime.datetime.now(timezone.utc)
utc_time = dt.replace(tzinfo=timezone.utc)
utc_timestamp = utc_time.timestamp()
return utc_timestamp
# create start and end timestamps
_now = datetime.datetime.now()
str_start = str(utc_converter(_now))
_end = _now + timedelta(seconds=10)
str_end = str(utc_converter(_end))
This is an answer which is significant for nowadays (python 3.9 or later).
Use strptime to create a datetime object from the timestring. Add 9 hours with timedelta, and match the time format with the timestring you have.
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
#You can then apply custom time formatting as well as a timezone.
TIMEZONE = [Add a timezone] #https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
custom_time_format = "%H:%M"
time_modification = datetime.fromtimestamp(timestring.timestamp(), ZoneInfo(TIMEZONE)).__format__(custom_time_format)
While I think it's more meaningful to apply a timezone, you don't necessarily need to, so you can also simply do that:
time_format = "%H:%M:%S"
timestring = datetime.strptime(str(datetime.now() + timedelta(hours=9))[11:19], time_format)
time_modification = datetime.fromtimestamp(timestring.timestamp())
datetime
https://docs.python.org/3/library/datetime.html
strftime-and-strptime-format-codes
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
timedelta
https://docs.python.org/3/library/datetime.html#datetime.timedelta
zoneinfo
https://docs.python.org/3/library/zoneinfo.html#module-zoneinfo

Converting unix timestamp string to readable date

I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime, I get a TypeError:
>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
Use datetime module:
from datetime import datetime
ts = int('1284101485')
# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)
Taken from http://seehuhn.de/pages/pdate
The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:
datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')
Where posix_time is the Posix epoch time you want to convert
>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'
There are two parts:
Convert the unix timestamp ("seconds since epoch") to the local time
Display the local time in the desired format.
A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:
#!/usr/bin/env python
from datetime import datetime
import tzlocal # $ pip install tzlocal
unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)
To display it, you could use any time format that is supported by your system e.g.:
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y")) # print date in your format
If you do not need a local time, to get a readable UTC time instead:
utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))
If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:
local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))
On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):
#!/usr/bin/env python3
from datetime import datetime, timezone
utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:
#!/usr/bin/env python
import time
unix_timestamp = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time))
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))
In Python 3.6+:
import datetime
timestamp = 1642445213
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")
Output (local time)
2022-01-17 20:46:53
Explanation
Line #1: Import datetime library.
Line #2: Unix time which is seconds since 1970-01-01.
Line #3: Converts this to a unix time object, check with: type(value)
Line #4: Prints in the same format as strp. Local time. To print in UTC see example below.
Bonus
To save the date to a string then print it, use this:
my_date = f"{value:%Y-%m-%d %H:%M:%S}"
print(my_date)
To output in UTC:
value = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
# 2022-01-17 18:50:52
Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:
Timestamps can be in two formats:
13 digits(milliseconds) -
To convert milliseconds to date, use:
import pandas
result_ms=pandas.to_datetime('1493530261000',unit='ms')
str(result_ms)
Output: '2017-04-30 05:31:01'
10 digits(seconds) -
To convert seconds to date, use:
import pandas
result_s=pandas.to_datetime('1493530261',unit='s')
str(result_s)
Output: '2017-04-30 05:31:01'
For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:
import os, datetime
datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")
Output:
'December 26, 2012'
You can convert the current time like this
t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'
To convert a date in string to different formats.
import datetime,time
def createDateObject(str_date,strFormat="%Y-%m-%d"):
timeStamp = time.mktime(time.strptime(str_date,strFormat))
return datetime.datetime.fromtimestamp(timeStamp)
def FormatDate(objectDate,strFormat="%Y-%m-%d"):
return objectDate.strftime(strFormat)
Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')
Output 03-03-2013
timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')
Get the readable date from timestamp with time also, also you can change the format of the date.
Note that utcfromtimestamp can lead to unexpected results since it returns a naive datetime object. Python treats naive datetime as local time - while UNIX time refers to UTC.
This ambiguity can be avoided by setting the tz argument in fromtimestamp:
from datetime import datetime, timezone
dtobj = datetime.fromtimestamp(1284101485, timezone.utc)
>>> print(repr(dtobj))
datetime.datetime(2010, 9, 10, 6, 51, 25, tzinfo=datetime.timezone.utc)
Now you can format to string, e.g. an ISO8601 compliant format:
>>> print(dtobj.isoformat(timespec='milliseconds').replace('+00:00', 'Z'))
2010-09-10T06:51:25.000Z
Use the following codes, I hope it will solve your problem.
import datetime as dt
print(dt.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))
Use datetime.strftime(format):
from datetime import datetime
unixtime = int('1284101485')
# Print with local time
print(datetime.fromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
# Print with UTC time
print(datetime.utcfromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
datetime.fromtimestamp(timestamp): Return the local date corresponding to the POSIX timestamp, such as is returned by time.time().
datetime.utcfromtimestamp(timestamp): Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None. (The resulting object is naive.)
import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
Another way that this can be done using gmtime and format function;
from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))
Output: 2018-10-4 11:57:44
If you are working with a dataframe and do not want the series cannot be converted to class int error. Use the code below.
new_df= pd.to_datetime(df_new['time'], unit='s')
i just successfully used:
>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date
You can use easy_date to make it easy:
import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")
quick and dirty one liner:
'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))
'2013-5-5-1-9-43'

Categories