plot only the time from datetime objects in matplot lib - python

I have a list of date and time values with the format '2019-08-24 08:57:18.550' for example. I have successfully converted them into numbers that matplotlib understands using datetime with the code matplotlib.dates.date2num(points) however I am having trouble getting matplotlib to plot only the time, not the associated date.
The graph it creates has tick marks with labels such as 08-24 12 which I assume has the format "month-date hour". I would like it to only plot the time, ideally with the format "hour:minute" or something along those lines. How do I get matplotlib to do this?

If I understood correctly, and it is the current date/time that you are looking for, then:
>>> from datetime import datetime
>>> current_time = datetime.now()
>>> current_time
datetime.datetime(2020, 5, 18, 22, 4, 41, 425538)
#################(year, month, day, hour, minute, second, microsecond)
You can then format it (this is what I didn't quite understand what you were asking), but if you wanted hour:minute format then:
from datetime import datetime
time = datetime.now()
hour = time.hour
minute = time.minute
print(f"{hour}:{minute}")
You should note that datetime.datetime(2020, 5, 18, 22, 4, 41, 425538) was not iterable.

Related

Calculating timedeltas across daylight saving

I'm facing a python timezones problem and am unsure of what is the right approach to deal with it. I have to calculate timedeltas from given start and end DateTime objects. It can happen that daylight saving time will change during the runtime of my events, so I have to take that into account.
So far I've learned that for this to work I need to save my start and end times as timezone aware DateTime objects rather than regular UTC DateTimes.
I've been looking into DateTime.tzinfo, pytz,and dateutil but from what I understand these are all mostly focused on localised display of UTC DateTime objects or calculating the offsets between different timezones. Other helpers I found expect the timezone as a UTC offset, so would already require me to know if a date is affected by daylight saving or not.
So, I guess my question is: Is there a way so save a DateTime as "Central Europe" and have it be aware of daytime savings when doing calculations with them? Or, if not, what would be the established way to check if two DateTime objects are within daylight saving, so I can manually adjust the result if necessary?
I'd be grateful for any pointers.
You just need to produce an aware (localised) datetime instance, then any calculation you do with it will take DST into account. Here as an example with pytz:
>>> import pytz
>>> from datetime import *
>>> berlin = pytz.timezone('Europe/Berlin')
>>> d1 = berlin.localize(datetime(2023, 3, 25, 12))
datetime.datetime(2023, 3, 25, 12, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CET+1:00:00 STD>)
>>> d2 = berlin.localize(datetime(2023, 3, 26, 12))
datetime.datetime(2023, 3, 26, 12, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
>>> d2 - d1
datetime.timedelta(seconds=82800)
>>> (d2 - d1).total_seconds() / 60 / 60
23.0

Create datetime object to use for comparison

How can I create a date time object for 9:00 AM UTC to use for comparison with the current utc time?
new_date = datetime.datetime(2019, 12, 2, 10, 24, 34, 198130)
I want to do it without the year, minutes and seconds.
If you don't need the date part of it, use datetime.time:
import datetime
nine_am = datetime.time(9)
if datetime.datetime.utcnow().time() > nine_am:
...

Python Time Subtraction Resulting into Time Tuple

I want to subtract 2 times and convert that into a time array.
I consulted this How to calculate the time interval between two time strings. Stating this following code
from datetime import datetime as dt
import time
print("Time Subtraction")
FMT = '%Y-%m-%d %H:%M:%S'
time_tuple = (2018, 1, 13, 13, 51, 18, 2, 317, 0)
time2_tuple = (2018, 1, 15, 13, 50, 18, 2, 317, 0)
s1 = time.strftime(FMT, time_tuple)
s2 = time.strftime(FMT, time2_tuple)
tdelta = dt.strptime(s2, FMT) - dt.strptime(s1, FMT)
print(tdelta)
The result is:
Time Subtraction
1 day, 23:59:00
But I want to get a tuple/print that will look like this
tuple = (0,0,1,23,59,0,2,317,0)
I usually use time not datetime so I am not sure what to do. Any ideas?
tdelta is a datetime.timedelta object, therefore you are printing the string representation of that object. You can get the days, hours, minutes, etc by performing simple arithmetic (since they are stored as fractions-of-days) on the attributes:
def days_hours_minutes(delta):
return delta.days, delta.seconds//3600, (delta.seconds//60)%60
You can add as many of these attributes to the tuple as you'd like.

In Python, how to get a localized timestamp with only the datetime package?

I have a unix timestamp in seconds (such as 1294778181) that I can convert to UTC using
from datetime import datetime
datetime.utcfromtimestamp(unix_timestamp)
Problem is, I would like to get the corresponding time in 'US/Eastern' (considering any DST) and I cannot use pytz and other utilities.
Only datetime is available to me.
Is that possible?
Thanks!
Easiest, but not supersmart solution is using timedelta
import datetime
>>> now = datetime.datetime.utcnow()
US/Eastern is 5 hours behind UTC, so let's just create thouse five hours as a timedelta object and make it negative, so that when reading back our code we can see that the offset is -5 and that there's no magic to deciding when to add and when to subtract timezone offset
>>> eastern_offset = -(datetime.timedelta(hours=5))
>>> eastern = now + eastern_offset
>>> now
datetime.datetime(2016, 8, 26, 20, 7, 12, 375841)
>>> eastern
datetime.datetime(2016, 8, 26, 15, 7, 12, 375841)
If we wanted to fix DST, we'd run the datetime through smoething like this (not entirely accurate, timezones are not my expertise (googling a bit now it changes each year, yuck))
if now.month > 2 and now.month < 12:
if (now.month == 3 and now.day > 12) or (now.month == 11 and now.day < 5):
eastern.offset(datetime.timedelta(hours=5))
You could go even into more detail, add hours, find out how exactly it changes each year... I'm not going to go through all that :)

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)

Categories

Resources