英文:
How to Generate Random Year in Python with format YYYY?
问题
age=random.randint(20, 80),
英文:
I have this code to generate fake name, age, address, I want to know what is the line to generate fake year in YYYY format?
def create_fake_users(n):
"""Generate fake users."""
faker = Faker()
for i in range(n):
user = User(name=faker.name(),
age=random.randint(20, 80),
address=faker.address().replace('\n', ', '),
phone=faker.phone_number(),
email=faker.email())
db.session.add(user)
db.session.commit()
print(f'Added {n} fake users to the database.')
答案1
得分: 1
你可以使用faker来生成随机日期:
from faker import Faker
fake = Faker()
# 从今天开始的一百年
fake.date_between(start_date='today', end_date='+100y')
# datetime.date(2038, 5, 10)
# 过去一百年
fake.date_time_between(start_date='-100y', end_date='now')
# datetime.datetime(1989, 10, 7, 19, 47, 27)
如果你只想获取年份 YYYY
:
fake.date_between(start_date='today', end_date='+100y').year
# 2038
fake.date_time_between(start_date='-100y', end_date='now').year
# 1989
英文:
You can use faker to generate random dates as well:
from faker import Faker
fake = Faker()
#one hundred years from today
fake.date_between(start_date='today', end_date='+100y')
#datetime.date(2038, 5, 10)
# last one hundred years
fake.date_time_between(start_date='-100y', end_date='now')
#datetime.datetime(1989, 10, 7, 19, 47, 27)
If you just want the year in YYYY
then:
fake.date_between(start_date='today', end_date='+100y').year
#2038
fake.date_time_between(start_date='-100y', end_date='now').year
#1989
答案2
得分: 1
我希望这对你的解决方案有用
from faker import Faker
import datetime
fake = Faker()
date = fake.date()
datetime_object = datetime.datetime.strptime(date, '%Y-%m-%d')
datetime_object.year
英文:
I hope, this works for your solution
from faker import Faker
import datetime
fake = Faker()
date = fake.date()
datetime_object = datetime.datetime.strptime(date, '%Y-%m-%d')
datetime_object.year
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论