Converting between time formats - python

Is there a way to convert time from the year_month_day-hh_mm_ss to timestapm (in milliseconds since 1971) with DateUtils? or some other library..
thanks.

Have a look at the Python datetime and time modules.
from datetime import datetime
d = datetime.strptime("2017_03_16-14:08:10", "%Y_%m_%d-%H:%M:%S")
This will create a datetime object of d
Then use mktime from Python's time module to get your timestamp
import time
time.mktime(d.timetuple())*1000
The *1000 is required to convert from seconds to milliseconds.
Also, do you mean 1971 or the Unix epoch (Jan 01 1970)?

Try the arrow module found at the following URL: https://pypi.python.org/pypi/arrow

You can parse the time with strptime, then you can get the time since epoch time in milliseconds by using strftime to format only seconds. Multiply by 1000 to get milliseconds.
converted_time.strftime("%s") * 1000

You can use timedelta
from datetime import timedelta
year = timedelta(days=(2017-1971)*365)#number of days from 1971 to 2017
mili_sec = (year.total_seconds())*1000#you will get total_seconds just mulitply with 1000 to get milliseconds
OUTPUT
1450656000000.0
OR
You wanted difference from a particular date.Ex from 1971-01-01 to 2017-03-16-14:08:10
from datetime import datetime
new_day = datetime.strptime("2017_03_16-14:08:10", "%Y_%m_%d-%H:%M:%S")
old_day = datetime.strptime("1971_01_01-00:00:00", "%Y_%m_%d-%H:%M:%S")
diff_day_milliseconds = ((new_day - old_day).total_seconds())*1000
OUTPUT
1458137290000.0

Related

python datetime calculation not trimming to milliseconds

Doing the following calculation to take 30 days of the current date using the date-time module. The calculation is correct but it's not trimming milliseconds to 3 digits. any idea how I can implement it?
from datetime import datetime,timedelta
datetime_limit = datetime.today().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
datetime_limit = datetime.today() - timedelta(days=30)
The last digits are added when you do the calculation with timedelta.
from datetime import datetime,timedelta
datetime_limit = str(datetime.today() - timedelta(days=30))[:-3]
print(datetime_limit)

How to convert milliseconds to time

I want to convert milliseconds to time. Please help me in that
from datetime import datetime
from dateutil.parser import parse
current = datetime.now()
print(current)
milli = current.microsecond
print(milli)
What do you mean milliseconds to time?
If you want datetime format, use
timenow=datetime.timedelta(milliseconds=999999)
print(timenow)
the output is
0:16:39.999000

Convert unix timestamp in Python to datetime and make 2 Hours behind

I have this code, recieve a unix timestamp from a server which is 2 hours ahead of my time. My time is SAST and theirs is GMT +2.
I convert this timestamp in python to a readable datetime like this
import datetime
unixtimestamp = 1507126064
datetime.datetime.fromtimestamp(unixtimestamp).strftime('%Y-%m-%d %H:%M:%S')
The problem is that this time comes back two hours ahead of me, so what would be the easiest way to minus two hours or make it local time.
With datetime.timedelta object:
from datetime import datetime, timedelta
unix_ts = 1507126064
dt = (datetime.fromtimestamp(unix_ts) - timedelta(hours=2)).strftime('%Y-%m-%d %H:%M:%S')
print(dt)

Python - How to convert datetime data using toordinal considering the time

Let's assume that I have the following data:
25/01/2000 05:50
When I convert it using datetime.toordinal, it returns this value:
730144
That's nice, but this value just considers the date itself. I also want it to consider the hour and minutes (05:50). How can I do it using datetime?
EDIT:
I want to convert a whole Pandas Series.
An ordinal date is by definition only considering the year and day of year, i.e. its resolution is 1 day.
You can get the microseconds / milliseconds (depending on your platform) from epoch using
datetime.datetime.strptime('25/01/2000 05:50', '%d/%m/%Y %H:%M').timestamp()
for a pandas series you can do
s = pd.Series(['25/01/2000 05:50', '25/01/2000 05:50', '25/01/2000 05:50'])
s = pd.to_datetime(s) # make sure you're dealing with datetime instances
s.apply(lambda v: v.timestamp())
If you use python 3.x. You can get date with time in seconds from 1/1/1970 00:00
from datetime import datetime
dt = datetime.today() # Get timezone naive now
seconds = dt.timestamp()

How to get UTC time in Python?

How do I get the UTC time, i.e. milliseconds since Unix epoch on Jan 1, 1970?
For Python 2 code, use datetime.utcnow():
from datetime import datetime
datetime.utcnow()
For Python 3, use datetime.now(timezone.utc) (the 2.x solution will technically work, but has a giant warning in the 3.x docs):
from datetime import datetime, timezone
datetime.now(timezone.utc)
For your purposes when you need to calculate an amount of time spent between two dates all that you need is to subtract end and start dates. The results of such subtraction is a timedelta object.
From the python docs:
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
And this means that by default you can get any of the fields mentioned in it's definition -
days, seconds, microseconds, milliseconds, minutes, hours, weeks. Also timedelta instance has total_seconds() method that:
Return the total number of seconds contained in the duration.
Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) *
106) / 106 computed with true division enabled.
Timezone-aware datetime object, unlike datetime.utcnow():
from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)
Timestamp in milliseconds since Unix epoch:
datetime.now(timezone.utc).timestamp() * 1000
In the form closest to your original:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return now
If you need to know the number of seconds from 1970-01-01 rather than a native Python datetime, use this instead:
return (now - datetime.datetime(1970, 1, 1)).total_seconds()
Python has naming conventions that are at odds with what you might be used to in Javascript, see PEP 8. Also, a function that simply returns the result of another function is rather silly; if it's just a matter of making it more accessible, you can create another name for a function by simply assigning it. The first example above could be replaced with:
utc_now = datetime.datetime.utcnow
import datetime
import pytz
# datetime object with timezone awareness:
datetime.datetime.now(tz=pytz.utc)
# seconds from epoch:
datetime.datetime.now(tz=pytz.utc).timestamp()
# ms from epoch:
int(datetime.datetime.now(tz=pytz.utc).timestamp() * 1000)
Timezone aware with zero external dependencies:
from datetime import datetime, timezone
def utc_now():
return datetime.utcnow().replace(tzinfo=timezone.utc)
From datetime.datetime you already can export to timestamps with method strftime. Following your function example:
import datetime
def UtcNow():
now = datetime.datetime.utcnow()
return int(now.strftime("%s"))
If you want microseconds, you need to change the export string and cast to float like: return float(now.strftime("%s.%f"))
you could use datetime library to get UTC time even local time.
import datetime
utc_time = datetime.datetime.utcnow()
print(utc_time.strftime('%Y%m%d %H%M%S'))
why all reply based on datetime and not time?
i think is the easy way !
import time
nowgmt = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
print(nowgmt)
To be correct, UTC format needs at least the T letter:
>>> a=(datetime.datetime.now(timezone.utc))
>>> a.strftime("%Y-%m-%dT%H:%M:%SZ")
'2022-11-28T16:42:17Z'

Categories

Resources