Convert timedelta "9:50:00" to String "09:50" - python

How can you convert the timedelta so that it only outputs "09:50" as a string instead of output: "9:50:00"?
from datetime import timedelta
y = 3
x = 30
time1 = timedelta(hours=6, minutes=20)
time2 = timedelta(hours=y, minutes=x)
future = time1 + time2
print(future)
future_str = str(future)
print(future_str)

Code that works is:
from datetime import datetime, timedelta
y = 3
x = 30
time1 = timedelta(hours=6, minutes=20)
time2 = timedelta(hours=y, minutes=x)
future = time1 + time2
s = (datetime(1, 1, 1) + future).strftime("%H:%M")
print(s)
>>> 09:50
Explanation: timedelta doesn't have strftime() method, that's why other answers are failing, so we need to convert it back to datetime, an easy trick is to add a dummy datetime object

If you already have string "9:50:00" you can just slice it.
future_str = "9:50:00"[0:4]

Try:
'{:0>8}'.format(future_str)[:5])

use strftime("%H:%M")
which helps to format your time example code below
future_str = future.strftime("%H:%M")
It return => 09:50

Related

python datetime with 6 digit milliseconds

How could I print 6 digit milli seconds in below format
>>> import datetime
>>> datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='milliseconds')
'2022-01-10T18:29:10.698000+05:30'
Actual Output:
'2022-01-10T18:29:10.108+05:30'
Expecting Output something like:
'2022-01-10T18:29:10.108000+05:30'
Use timespec=microseconds:
>>> dt = datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='microseconds')
'2022-01-10T14:05:55.742931+01:00'
Update:
If you want 0 for microsecond value, you can do:
now = datetime.datetime.now().astimezone()
now = now.replace(microsecond=now.microsecond // 1000 * 1000)
now = now.isoformat(timespec='microseconds')
print(now)
# Output
'2022-01-10T14:17:08.386000+01:00'
There are only 1000ms in 1 second, do you mean microseconds?
datetime.datetime.now(tz = datetime.datetime.now().astimezone().tzinfo).isoformat(timespec='microseconds')
If you want utc and milliseconds value, you can do
UTC Convertion
import pytz
from datetime import datetime
epoch: datetime = datetime.now().replace(tzinfo=pytz.utc)
print(epoch)

Timestamp conversion and find its difference

I have the following two timestamps
time1 = 2018-05-13 13:06:30
time2 = 2018-05-14T13:49:37.140Z
How to find the difference from it? I am looking for an output that tells the difference in the number of hours in python. The example above case is approx. 23hrs.
Take a look at python datetime model
Anyway, it looks like you have 2 types of string representations of a date, so:
import datetime
time1 = "2018-05-13 13:06:30"
time2 = "2018-05-14T13:49:37.140Z"
time1 = datetime.datetime.strptime(time1, '%Y-%m-%d %H:%M:%S')
time2 = datetime.datetime.strptime(time2, '%Y-%m-%dT%H:%M:%S.%fZ')
print((time2 - time1).total_seconds()/60/60)

How can I truncate milliseconds to 2 most significant decimals in strftime()

I have a datetime object that is printed with:
from datetime import datetime
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").strip()
print('TS: {}'.format(ts))
# "2020-12-03 02:13:27.823467"
However, I only want the first 2 digits of the milliseconds to be shown, like this: 2020-12-03 02:13:27.82. Using "%.2f" didn't work, and perhaps there's another time function more suitable?
What is the best way to do this without introducing (possibly laggy) regex string manipulations?
What about something like the following?
import datetime
now = datetime.datetime.now()
ts = now.strftime('%Y-%m-%d %H:%M:%S') + '.{:02d}'.format(round(now.microsecond, -4))[:3]
print('TS: {}'.format(ts))
# TS: 2020-12-03 01:22:01.86
EDIT
Perhaps a better parametrized solution would be:
import datetime
def largest_digits(value, num_digits=2, max_digits=6):
discard_digits = num_digits - max_digits
base = 10 ** -discard_digits
return f'{round(value, discard_digits) // base:02d}'
now = datetime.datetime.now()
ts = now.strftime('%Y-%m-%d %H:%M:%S') + '.' + largest_digits(now.microsecond, 2)
print('TS: {}'.format(ts))
# TS: 2020-12-03 01:22:01.86
Aaahi, the answer was trivial! Use string selection.
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").strip()[:-4]

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;
}

Subtracting Dates of Different Formats and converting to Int

I asked a similar question earlier and got some great feedback. I combined several answers to arrive at a solution, but it seems highly inefficient. I'm looking for a better way to get the total number of days between a variable (ts) and today in the form of an integer.
My Code:
import datetime
ts = '2015-03-01T17:09:00.000+0000'
ts = ts[:10]
f = '%Y-%m-%d'
date_from_sql = datetime.datetime.strptime(ts, f)
now = datetime.datetime.now()
now = str(now)
now = now[:10]
now = datetime.datetime.strptime(str(now), f)
delta = date_from_sql - now
print delta.total_seconds()/(3600*24)
Output:
67.0
delta.total_seconds()/(3600*24) is not needed, just get use .days
from datetime import datetime
now = datetime.now()
ts = '2015-03-01T17:09:00.000+0000'
ts = ts[:10]
f = '%Y-%m-%d'
date_from_sql = datetime.strptime(ts, f)
print(date_from_sql - now).days
If you dont want to take the time into account just use dates:
now = datetime.now().date()
ts = '2015-03-01T17:09:00.000+0000'
ts = ts[:10]
f = '%Y-%m-%d'
date_from_sql = datetime.strptime(ts, f).date()
print(date_from_sql - now).days
If there is a chance the date string may be in different formats you might want dateutil:
from dateutil import parser
now = datetime.now().date()
ts = '2015-03-01T17:09:00.000+0000'
ts = parser.parse(ts).date()
print(ts - now).days
#Padraic, yes agree, My solution also same,
from datetime import datetime
ts = '2015-03-01T17:09:00.000+0000'
print "days:-", (datetime.strptime(ts[:10], '%Y-%m-%d').date() - datetime.now().date()).days
If you don't care about the time of the day (and timezones) i.e., the result has a day resolution; you could use datetime.date class and .toordinal() method to get the number of days:
from datetime import date
ts = '2015-03-01T17:09:00.000+0000'
date_from_sql = date(*map(int, ts[:10].split('-')))
print(date_from_sql.toordinal() - date.today().toordinal())
# -> 66

Categories