Date Time Format Unknown [duplicate] - python

This question already has answers here:
How to convert integer timestamp into a datetime
(3 answers)
Closed last year.
I am trying to figure out a time format used by someone else. In addition to the date, I have time with an example being the following:
1641859200000
I cant seem to figure out what time or date time format this is. It cannot be HHMMSS, because in this example the second is 85, which is not possible. Any idea what format this is, and how I can convert it using Python to HH:MM:SS ?
Thank you :)

You have a timestamp in seconds from Epoch since January 1, 1970 (midnight UTC/GMT). To convert to a datetime, use:
from datetime import datetime
print(datetime.fromtimestamp(1641859200000 / 1000))
# Output
2022-01-11 01:00:00
Note: you have to divide by 1000 because this timestamp contains milliseconds and Epoch should be in seconds.

This is a Unix-Timestamp.
You can convert in a human-readable format like this:
from datetime import datetime
timestamp = 1641859200000/1000
dt = datetime.fromtimestamp(timestamp)
print(dt)
Edit: didn't check the actual timestamp, whyever, this has to be divided by 1000 as done in the othe answer.

This probably is a unix timestamp https://en.wikipedia.org/wiki/Unix_time. The factor 1000 stems from a millisecond representation I think. Depends on, from where you got this stamp.
You can convert it using:
>>> datetime.datetime.fromtimestamp(1641859200000/1000)
datetime.datetime(2022, 1, 11, 1, 0)

Take a look at dateparser https://dateparser.readthedocs.io/.
It will help you figure out what the date and time is based on the range of input date strings:
pip install dateparser
>>> import dateparser
>>> dateparser.parse('1641859200000')
datetime.datetime(2022, 1, 11, 1, 0)
Your timestamp is miliseconds since Unix epoch in this case but if you ever run into similar problem dateparser could help you.
Regarding the second part of the question. Convertion to HH:MM:SS format
>> dt = datetime.datetime(2022, 1, 11, 1, 0)
>> dt.strftime("%H:%M:%S")
'01:00:00'
Additional info: Available Format Codes

Related

Convert seconds since 1-1-1999 to UTC date/time in Python

I have an list of timestamps in the form of seconds since January 1, 1999 00:00 UTC (not epoch). I am looking for a way to convert this to a date/time in a more standard format (like YYYY-MM-DD HH:MM:SS UTC). I'm not sure how to do this since its not that more usual "seconds since epoch" format.
Thanks.
Figured it out with some simple datetime and timedelta stuff
d0 = datetime(1999,1,1,0,0,0)
dt = timedelta(seconds = time[0])
d = d0 + dt
>>> d
datetime.datetime(2016, 8, 19, 13, 28, 55, 317013)
I'm not pretty sure about what do you need exactly, but I hope that this can help you:
x = datetime.datetime(1999,1,1)
y=x + datetime.timedelta(0,1256083200.0)
print('{:%Y-%m-%d %H:%M:%S}'.format(y))
#print:'2038-10-21 00:00:00'
Reference:
What is the standard way to add N seconds to datetime.time in Python?
How to convert a Python datetime object to seconds
How can I create basic timestamps or dates? (Python 3.4)

Parse and combine date and time (leap seconds) from strings - python

I parse a date (format: YYYY-MM-DD HH:MM:SS) from a data file which contains multiple lines of dates.
The problem is that the data contains leap seconds so i'm not able to use datetime. How can I take into account the leap seconds (0-60), so that at the end I would have the same result if I would have used datetime.strptime from the string with the format above (thus, date+time), please?
I have already tried with combine using date for the date and time for the time string. Is it the right way or are there some others?
Thanks in advance.
Just use time.strptime():
#!/usr/bin/env python
import datetime as DT
import time
from calendar import timegm
utc_time_string = '2012-06-30 23:59:60'
utc_time_tuple = time.strptime(utc_time_string, "%Y-%m-%d %H:%M:%S")[:6]
utc_dt = DT.datetime(1970, 1, 1) + DT.timedelta(seconds=timegm(utc_time_tuple))
# -> datetime.datetime(2012, 7, 1, 0, 0)
If the input time is not in UTC then you could handle the leap second in the time_tuple manually e.g., the datetime module may raise ValueError if you pass the leap second directly or it may silently truncate 60 to 59 if it encounters a leap second in indirect (internal) calls.

Getting today's date in YYYY-MM-DD in Python?

Is there a nicer way than the following to return today's date in the YYYY-MM-DD format?
str(datetime.datetime.today()).split()[0]
Use strftime:
>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'
To also include a zero-padded Hour:Minute:Second at the end:
>>> datetime.today().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-26 16:50:03'
To get the UTC date and time:
>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-27 00:50:03'
You can use datetime.date.today() and convert the resulting datetime.date object to a string:
from datetime import date
today = str(date.today())
print(today) # '2017-12-26'
I always use the isoformat() method for this.
from datetime import date
today = date.today().isoformat()
print(today) # '2018-12-05'
Note that this also works on datetime objects if you need the time in the standard ISO 8601 format as well.
from datetime import datetime
now = datetime.today().isoformat()
print(now) # '2018-12-05T11:15:55.126382'
Very late answer, but you can simply use:
import time
today = time.strftime("%Y-%m-%d")
# 2023-02-08
Datetime is just lovely if you like remembering funny codes. Wouldn't you prefer simplicity?
>>> import arrow
>>> arrow.now().format('YYYY-MM-DD')
'2017-02-17'
This module is clever enough to understand what you mean.
Just do pip install arrow.
Addendum: In answer to those who become exercised over this answer let me just say that arrow represents one of the alternative approaches to dealing with dates in Python. That's mostly what I meant to suggest.
Are you working with Pandas?
You can use pd.to_datetime from the pandas library. Here are various options, depending on what you want returned.
import pandas as pd
pd.to_datetime('today') # pd.to_datetime('now')
# Timestamp('2019-03-27 00:00:10.958567')
As a python datetime object,
pd.to_datetime('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 50, 42, 587629)
As a formatted date string,
pd.to_datetime('today').isoformat()
# '2019-04-18T04:03:32.493337'
# Or, `strftime` for custom formats.
pd.to_datetime('today').strftime('%Y-%m-%d')
# '2019-03-27'
To get just the date from the timestamp, call Timestamp.date.
pd.to_datetime('today').date()
# datetime.date(2019, 3, 27)
Aside from to_datetime, you can directly instantiate a Timestamp object using,
pd.Timestamp('today') # pd.Timestamp('now')
# Timestamp('2019-04-18 03:43:33.233093')
pd.Timestamp('today').to_pydatetime()
# datetime.datetime(2019, 4, 18, 3, 53, 46, 220068)
If you want to make your Timestamp timezone aware, pass a timezone to the tz argument.
pd.Timestamp('now', tz='America/Los_Angeles')
# Timestamp('2019-04-18 03:59:02.647819-0700', tz='America/Los_Angeles')
Yet another date parser library: Pendulum
This one's good, I promise.
If you're working with pendulum, there are some interesting choices. You can get the current timestamp using now() or today's date using today().
import pendulum
pendulum.now()
# DateTime(2019, 3, 27, 0, 2, 41, 452264, tzinfo=Timezone('America/Los_Angeles'))
pendulum.today()
# DateTime(2019, 3, 27, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))
Additionally, you can also get tomorrow() or yesterday()'s date directly without having to do any additional timedelta arithmetic.
pendulum.yesterday()
# DateTime(2019, 3, 26, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))
pendulum.tomorrow()
# DateTime(2019, 3, 28, 0, 0, 0, tzinfo=Timezone('America/Los_Angeles'))
There are various formatting options available.
pendulum.now().to_date_string()
# '2019-03-27'
pendulum.now().to_formatted_date_string()
# 'Mar 27, 2019'
pendulum.now().to_day_datetime_string()
# 'Wed, Mar 27, 2019 12:04 AM'
Rationale for this answer
A lot of pandas users stumble upon this question because they believe it is a python question more than a pandas one. This answer aims to be useful to folks who are already using these libraries and would be interested to know that there are ways to achieve these results within the scope of the library itself.
If you are not working with pandas or pendulum already, I definitely do not recommend installing them just for the sake of running this code! These libraries are heavy and come with a lot of plumbing under the hood. It is not worth the trouble when you can use the standard library instead.
from datetime import datetime
date = datetime.today().date()
print(date)
Use f-strings, they are usually the best choice for any text-variable mix:
from datetime import date
print(f'{date.today():%Y-%m-%d}')
Taken from Python f-string formatting not working with strftime inline which has the official links as well.
If you need e.g. pacific standard time (PST) you can do
from datetime import datetime
import pytz
tz = pytz.timezone('US/Pacific')
datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')
# '2021-09-02 10:21:41'
my code is a little complicated but I use it a lot
strftime("%y_%m_%d", localtime(time.time()))
reference:'https://strftime.org/
you can look at the reference to make anything you want
for you what YYYY-MM-DD just change my code to:
strftime("%Y-%m-%d", localtime(time.time()))
This works:
from datetime import date
today =date.today()
Output in this time: 2020-08-29
Additional:
this_year = date.today().year
this_month = date.today().month
this_day = date.today().day
print(today)
print(this_year)
print(this_month)
print(this_day)
To get day number from date is in python
for example:19-12-2020(dd-mm-yyy)order_date
we need 19 as output
order['day'] = order['Order_Date'].apply(lambda x: x.day)

How to convert time object to minutes in python

I have an output from a database(postgreSQL) in python. The time is encoded as timestamptz. We need to be able to convert the time into just minutes.
2015-07-09 13:45:08.266520+00:00
For example this would be 825 minutes.
I'm having issues with the datetime.datetime formating, I just need to be able to drop everything but hours and minutes and then convert to minutes.
time_format = '%H:%M'
time1 = datetime.strptime('2015-07-09 13:45:08.266520+00:00', time_format)
So I'm trying to sort a big list of times into certain intervals. I need these times to be in just minutes in order to do any math on them, I do not want to have to mess with time anymore. Thats why I'm trying to just covert them into minutes by taking the hours * 60 + minutes. Since this is in a time format I cannot do any of that.
Substract the DateTime from a DateTime with the the reference point in time, extract the total_seconds from the resulting TimeDelta and divide by 60.
(You did not give any code. So I can't give any code based on your's.)
dateutil takes a lot of the headache out of parsing a ISO 8601 stamp:
>>> import dateutil.parser
>>> dateutil.parser.parse('2015-07-09 13:45:08.266520+00:00')
datetime.datetime(2015, 7, 9, 13, 45, 8, 266520, tzinfo=tzutc())
Since you want the answer to be '825 minutes', algebraically, you must be seeking an offset from an epoch mark:
>>> import datetime as dt
>>> mark=dateutil.parser.parse('2015-07-09 13:45:08.266520+00:00')-dt.timedelta(minutes=825)
>>> mark
datetime.datetime(2015, 7, 9, 0, 0, 8, 266520, tzinfo=tzutc())
So now use mark as the basis to calculate minute offsets. (You probably mean to ignore microseconds in the base time mark)
I understand what you're trying to do. So you want to convert the timestamp you're getting from your DB into minutes. Basically 0:00 would be 0, 1:00 would be 60 and so on.
Timestamps are standard, so a dirty hack you could do is just pull the indices of the relevant information that you want and go from there.
time = "2015-07-09 13:45:08.266520+00:00"
data = time[11:18]
print data //Will be 13:45:08
Then you can do data operations from there.

Converting date formats python - Unusual date formats - Extract %Y%M%D

I have a large data set with a variety of Date information in the following formats:
DAYS since Jan 1, 1900 - ex: 41213 - I believe these are from Excel http://www.kirix.com/stratablog/jd-edwards-date-conversions-cyyddd
YYDayofyear - ex 2012265
I am familiar with python's time module, strptime() method, and strftime () method. However, I am not sure what these date formats above are called on if there is a python module I can use to convert these unusual date formats.
Any idea how to get the %Y%M%D format from these unusual date formats without writing my own calculator?
Thanks.
You can try something like the following:
In [1]: import datetime
In [2]: s = '2012265'
In [3]: datetime.datetime.strptime(s, '%Y%j')
Out[3]: datetime.datetime(2012, 9, 21, 0, 0)
In [4]: d = '41213'
In [5]: datetime.date(1900, 1, 1) + datetime.timedelta(int(d))
Out[5]: datetime.date(2012, 11, 2)
The first one is the trickier one, but it uses the %j parameter to interpret the day of the year you provide (after a four-digit year, represented by %Y). The second one is simply the number of days since January 1, 1900.
This is the general conversion - not sure of your input format but hopefully this can be tweaked to suit it.
On the Excel integer to Python datetime bit:
Note that there are two Excel date systems (one 1-Jan-1900 based and another 1-Jan 1904 based); see https://support.microsoft.com/en-us/help/214330/differences-between-the-1900-and-the-1904-date-system-in-excel for more information.
Also note that the system is NOT zero-based. So, in the 1900 system, 1-Jan-1900 is day 1 (not day 0).
import datetime
EXCEL_DATE_SYSTEM_PC=1900
EXCEL_DATE_SYSTEM_MAC=1904
i = 42129 # Excel number for 5-May-2015
d = datetime.date(EXCEL_DATE_SYSTEM_PC, 1, 1) + datetime.timedelta(i-2)
Both of these formats seems pretty straightforward to work with. The first one, in fact, is just an integer, so why don't you just do something like this?
import datetime
def days_since_jan_1_1900_to_datetime(d):
return datetime.datetime(1900,1,1) + \
datetime.timedelta(days=d)
For the second one, the details depend on exactly how the format is defined (e.g. can you always expect 3 digits after the year even when the number of days is less than 100, or is it possible that there are 2 or 1 – and if so, is the year always 4 digits?) but once you've got that part down it can be done very similarly.
According to http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
, day of the year is "%j", whereas the first case can be solved by toordinal() and fromordinal(): date.fromordinal(date(1900, 1, 1).toordinal() + x)
I'd think timedelta.
import datetime
d = datetime.timedelta(days=41213)
start = datetime.datetime(year=1900, month=1, day=1)
the_date = start + d
For the second one, you can 2012265[:4] to get the year and use the same method.
edit: See the answer with %j for the second.
from datetime import datetime
df(['timeelapsed'])=(pd.to_datetime(df['timeelapsed'], format='%H:%M:%S') - datetime(1900, 1, 1)).dt.total_seconds()

Categories

Resources